玩笑/打字稿:导入文件中断了另一个文件的导入

问题描述 投票:0回答:1

我在单元测试中遇到一个奇怪的问题,开玩笑说我不知道​​如何解决。当我在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'
};

有什么想法吗?

typescript jestjs
1个回答
0
投票

您可能具有循环依赖关系,但是从您发布的截断的示例代码中我无法分辨。但是由于竞赛条件的原因,循环探矿可能导致进口货物显示为不确定状态。您可以使用eslint-plugin-import/no-cycle规则检查循环深度,然后将其重构出代码库。

© www.soinside.com 2019 - 2024. All rights reserved.