[英]Jest always received undefined for ES6 imported class method
我只是在做一个虚拟的 Jest 测试,它总是说 received: undefined。
例子:
/src/disjoint-set/index.ts
export default class DisjointSet {
public foo() {
return true;
}
}
/src/不相交集/测试
import DisjointSet from '..';
describe('It tests Disjoint DataScture', () => {
it('Should create a Disjoint Set', () => {
const disSet = new DisjointSet();
expect(disSet).toBeTruthy();
expect(disSet.foo()).toBe(true);
});
});
我的控制台 output:
src/data-structures/disjoint-set/ tests /disjoint-set.test.ts 它测试不相交的 DataScture ✕ 应该创建一个不相交的集合(5 毫秒)
● 它测试 Disjoint DataScture › 应该创建一个 Disjoint Set
expect(received).toBe(expected) // Object.is equality Expected: true Received: undefined 7 | expect(disSet).toBeTruthy(); 8 | > 9 | expect(disSet.foo()).toBe(true); | ^ at Object.<anonymous> (src/data-structures/disjoint-set/__tests__/disjoint-set.test.ts:9:26)
我的 package.json
{
"name": "leetcode",
"version": "1.0.0",
"description": "This is to test my data structure and algorithms in JavaScript",
"main": "index.js",
"scripts": {
"test": "jest",
"build": "tsc -p tsconfig.build.json"
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [
"leetcode",
"javascript"
],
"author": "",
"license": "MIT",
"bugs": {
"url": ""
},
"homepage": "",
"devDependencies": {
"@types/jest": "^27.4.1",
"jest": "^27.5.1",
"ts-jest": "^27.1.4",
"typescript": "^4.6.3"
},
"dependencies": {
"node-fetch": "^2.6.7",
"ts-node": "^10.7.0"
}
}
我的tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"types": ["node", "jest"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"baseUrl": ".",
"noFallthroughCasesInSwitch": true,
"outDir": "./dist",
"jsx": "preserve"
},
"compileOnSave": true,
"include": ["."]
}
我的 jest.config.ts
// jest.config.ts
import type { Config } from "@jest/types"
const config = {
preset: "ts-jest",
testEnvironment: "node",
verbose: true,
automock: true,
testPathIgnorePatterns: ['/dist']
}
export default config;
在您的class DisjointSet
中, public foo() {}
应该是foo() {}
。
class DisjointSet { foo() { return true; } } const obj = new DisjointSet(); console.log(obj.foo());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.