使用 TypeScript 进行的 Jest 测试无法识别导入别名

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

我正在为我的 Web 应用程序设置测试,该应用程序使用 Jest 框架,通过 TypeScript 与 Vue 框架配合使用。一切似乎都工作正常,除了我的导入中的

@
符号,例如
import { Foo } from '@/bar
。无论是在我的测试文件中还是在源代码中,它都无法理解并返回:

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

这是我在

package.json
中的 Jest 配置:

  "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"]
  }

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

谢谢你

typescript unit-testing testing jestjs babel-jest
3个回答
7
投票

我最终找到了一个解决方案,我将其附加到我的 Jest 配置中

package.json

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

3
投票

来自

ts-jest
文档 路径映射 部分:

// 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>/' } */),
}

0
投票

就我而言,只有在以编程方式指定 tsconfig.json 中的每个目录路径后,我才能使其工作。例如:

    "paths": {
      "@*": [
        "./src/*",
      ],
      "@components/*": ["src/components/*"],
      "@state/*": ["src/state/*"],
      "@test-utils/*": ["src/test-utils/*"]
    },
© www.soinside.com 2019 - 2024. All rights reserved.