我在单元测试中遇到一个奇怪的问题,开玩笑说我不知道如何解决。当我在file2.ts
中导入文件时,在file1.ts
中相同文件的导入变为undefined
。应用程序会生成并运行,但是单元测试不再起作用,并在file1.ts
中引发以下错误:
TypeError: Cannot read property 'getModel' of undefined
这是代码:
file1.ts
import users from '../users';
const model = users.getModel();
...
file2.ts
import users from '../../users';
const model = users.getModel();
...
users.ts
export class User {
getModel() {
...
}
}
export default new User();
file2.ts
的单元测试引发了file1.ts
的错误,即使我仅针对file2.ts
进行了单元测试。
如果我注释掉const model = users.getModel();
中的file2.ts
,则不会引发错误。
这是我的tsconfig.json
和我的jest.config.js
文件:
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"pretty": true,
"sourceMap": false,
"target": "es6",
"resolveJsonModule": true,
"esModuleInterop": true,
"allowJs": true,
"outDir": "./dist",
"baseUrl": "./src"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"dist",
"node_modules",
"**/*.spec.ts"
]
}
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverage: true,
coverageDirectory: './test-coverage'
};
有什么想法吗?
您可能具有循环依赖关系,但是从您发布的截断的示例代码中我无法分辨。但是由于竞赛条件的原因,循环探矿可能导致进口货物显示为不确定状态。您可以使用eslint-plugin-import/no-cycle规则检查循环深度,然后将其重构出代码库。