使用TypeScript编写的Jest测试无法识别导入别名。

7

我正在为我的 Web 应用程序设置测试,该应用程序使用 Vue 框架与 TypeScript,并使用 Jest 框架。除了带有 @ 符号的导入(例如 import { Foo } from '@/bar')之外,一切似乎都可以正常工作。无论它出现在我的测试文件还是源代码中,它都不能理解并返回以下结果:

Cannot find module '@/store' from 'src/tests/foo.spec.ts'

这是我的 Jest 配置文件,位于 package.json 中:

  "jest": {
    "moduleFileExtensions": [
      "js",
      "ts",
      "json",
      "vue"
    ],
    "testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "transform": {
      ".*\\.(vue)$": "vue-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.jsx?$": "babel-jest"
    },
    "testURL": "http://localhost/",
    "collectCoverage": true,
    "collectCoverageFrom": ["**/*.{ts,vue}", "!**/node_modules/**"],
    "coverageReporters": ["html", "text-summary"]
  }

有人知道如何使其正常工作吗?

谢谢。

2个回答

5

最终我找到了解决方法,我将下面这段代码添加到了package.json中的Jest配置中:

"moduleNameMapper": {
  "^@/(.*)$": "<rootDir>/src/$1"
},

3

来自 ts-jest 文档的 path-mapping 部分:

// jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest/utils')
// In the following statement, replace `./tsconfig` with the path to your `tsconfig` file
// which contains the path mapping (ie the `compilerOptions.paths` option):
const { compilerOptions } = require('./tsconfig')

module.exports = {
  // [...]
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths /*, { prefix: '<rootDir>/' } */),
}

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