ts-jest (TypeScript Jest) 中的映射路径出现问题,找不到模块

2024-02-18

I want to implement some jest tests in my backend and so I was trying to map my paths that I have configured in tsconfig.json via the moduleNameMapper of jest.config.js but when I run the tests I find the file is still not imported and I am shown this error on line 8 ⬇
error received from running test

Please assist me to map my paths correctly, I would highly appreciate any help.
To help you assist me here are the important files.
jest.config.js (where jest is usually configured) ⬇

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ["**/***.test.ts"],
  verbose: true,
  forceExit: true,
  
  moduleNameMapper: {
    '@util/(.*)': '<rootDir>/src/util/$1'
  }
};

tsconfig.json(打字稿的正常配置文件)⬇

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "baseUrl": "src",
    "paths": {
      "@util/*": ["util/*"]
    },
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

我创建了一个名为.babelrc包含以下内容⬇:

{
  "presets": ["@babel/preset-env"]
}

然后我配置了jest.config.js如下图⬇

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  transform: {
    '^.+\\.ts$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
    '^.+\\.mjs$': 'babel-jest',
  },
  moduleDirectories: ['node_modules', '<rootDir>/src'],
  moduleNameMapper: {
    '@controllers/(.*)': '<rootDir>/src/controllers/$1',
    '@middleware/(.*)': '<rootDir>/src/middleware/$1',
    '@models/(.*)': '<rootDir>/src/models/$1',
    '@routes/(.*)': '<rootDir>/src/routes/$1',
    '@types/(.*)': '<rootDir>/src/types/$1',
    '@util/(.*)': '<rootDir>/src/util/$1',
  }
};

然后我配置了 tsconfig.json,如下所示⬇:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "baseUrl": "src",
    "paths": {
      "@util/*": ["util/*"]
    },
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "types": ["jest"]
  }
}

感谢 Benjamin Drury 和@Ashok 的大力支持。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ts-jest (TypeScript Jest) 中的映射路径出现问题,找不到模块 的相关文章

随机推荐