绝对路径(baseUrl)出现错误:找不到模块。

177

我正在设置一个配置,以在create-react-app + typescript应用程序中运行我的测试(我已经弹出)。 我正在使用jest + enzyme。 在我的tsconfig.json中,我设置了baseUrl='./src',因此当我导入模块时,我可以使用绝对路径。 例如,这是我文件中的典型导入语句:

import LayoutFlexBoxItem from 'framework/components/ui/LayoutFlexBoxItem';

您可以看到路径是绝对的(从/src文件夹),而不是相对的。 当我在调试模式下运行时(yarn start),这很好用。

但是当我运行我的测试(yarn test)时,我会收到以下错误:

 Cannot find module 'framework/components/Navigation' from 'index.tsx'

看起来jest无法解析这个绝对路径,尽管我已经在tsconfig.json中设置了它。这是我的tsconfig.json:

{
  "compilerOptions": {
    "outDir": "dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "baseUrl": "./src"    
  },
  "exclude": [
    "node_modules",
    "build",
    "dist",
    "config",    
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}

现在我可以看到项目根目录下生成了一个tsconfig.test.json。这是用于测试的ts配置文件。以下是它的内容:
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs"
  }
}

正如您所看到的,“module”在此处为commonjs,而在默认配置中为esnext。这可能是一个原因吗?

有人能够使用Jest和绝对路径对其TypeScript项目进行单元测试吗?还是这是一个已知的错误?由于我已经从默认配置中退出,是否有一些设置要放在我的webpack配置中?

感谢您的意见和建议。

21个回答

0
如果您有一个单一代码库,其中每个项目都有自己的 tsconfig.json 文件,并且这些文件都是从基础(根)tsconfig.json 继承而来的,同时每个项目都有自己的 jest.config.js 文件,并且您从项目根目录启动测试,则应将您的 moduleNameMapper 添加到项目 根目录 中的 jest.config.js 文件中。
例如:
backend/
 - tsconfig.json
 - jest.config.js

frontend/
 - tsconfig.json
 - jest.config.js

/
- tsconfig.json
- jest.config.js

你的问题在jest测试中的frontend/,它有一个类似于tsconfig的配置文件:

{
  "compilerOptions": {
    "jsx": "react-native",
    "paths": {
      "src/*": ["client/src/*"]
    },
    "noEmit": true
  },
  "extends": "../tsconfig.json"
}

然后将这个添加到 root jest.config 应该可以解决这个问题:

  moduleNameMapper: {
    'src/(.*)': '<rootDir>/client/src/$1',
  },

所以总的来说,就像这样:

module.exports = {
  testEnvironment: 'node',
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
  testPathIgnorePatterns: ['cdk.out/'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  modulePathIgnorePatterns: ['tests'],
  globals: {
    'ts-jest': {
      isolatedModules: true,
    },
  },
  moduleNameMapper: {
    'src/(.*)': '<rootDir>/client/src/$1',
  },
};

可能有点显然,但我还是想加入这个回答,因为在其他的回答中没有涉及到此情况,而单体库仍然存在 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接