解析 jest.mock 中的 TypeScript 路径

Resolve TypeScript path in jest.mock

我正在向使用 compilerOptions.paths 的 TypeScript 项目添加单元测试,我需要模拟导入。

我 运行 遇到一个问题,jest 无法将模块解析为 mock

 FAIL  logic/index.test.ts
  ● Test suite failed to run

    Cannot find module '@lib/foo' from 'logic/index.test.ts'

我正在使用 ts-jest,它增加了对导入路径的支持,但看起来我需要为 mocks 做一个额外的步骤

这里解析路径的正确方法是什么?


简化案例

{
  "baseUrl": ".",
  "compilerOptions": {
    "paths": {
      "@lib/*": ["lib/*"]
    }
  }
}

文件系统

* lib
  * __mocks__
    * foo.ts
  * foo.ts
* logic
  * index.ts
  * index.test.ts
* tsconfig.json
* jest.config.js
// index.ts
import foo from '@lib/foo';

const logic = () => foo();

export default logic;
// index.test.ts
import 'jest';

import logic from '.';

jest.mock('@lib/foo');
// jest.config.js
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

根据 the ts-jest docs,当您使用 compilerOptions.paths 时,您需要相应地更新 Jest 的 moduleNameMapper。该库提供了一个实用程序来为您构建适当的映射:

// jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest/utils');

const { compilerOptions } = require('path/to/tsconfig');

module.exports = {
  moduleNameMapper: pathsToModuleNameMapper(
    compilerOptions.paths,
    { prefix: '<rootDir>/' },
  ),
  preset: 'ts-jest',
  testEnvironment: 'node',
};

或者您可以手动完成,在您的情况下:

// jest.config.js
module.exports = {
  moduleNameMapper: { '^@lib/(.*)$': '<rootDir>/lib/' },
  preset: 'ts-jest',
  testEnvironment: 'node',
};