【问题标题】:Resolve TypeScript path in jest.mock解析 jest.mock 中的 TypeScript 路径
【发布时间】:2021-06-15 22:49:27
【问题描述】:

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

我遇到了一个问题,即 jest 无法解析要模拟的模块

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

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

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

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


简化案例

{
  "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',
};

【问题讨论】:

  • 您的项目是如何设置的?您是否按照指示heregithub.com/kulshekhar/ts-jest/issues/1165 建议这个问题在于 Jest 如何处理模拟。
  • @jonrsharpe 啊,可能在玩笑配置中错过了moduleNameMapper,现在尝试..
  • @jonrsharpe 谢谢,从moduleNameMapper 丢失了'^@lib/(.*)$': '<rootDir>/lib/$1',;如果您发布作为答案,我会接受

标签: typescript unit-testing jestjs ts-jest


【解决方案1】:

根据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/$1' },
  preset: 'ts-jest',
  testEnvironment: 'node',
};

【讨论】:

  • 使用 pathsToModuleNameMapper 仍然无法正常工作,因为它不会转到 &lt;rootDir&gt;,我必须手动指定映射,但这是缺少的
  • @PaulS。更新了,该实用程序也提供了!
猜你喜欢
  • 2017-03-17
  • 2019-03-01
  • 1970-01-01
  • 2022-01-15
  • 2021-11-10
  • 2020-05-06
  • 2021-12-08
  • 2023-04-07
  • 2016-11-17
相关资源
最近更新 更多