You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jest时模块无法解析问题的解决方案咨询

解决Jest无法解析TypeScript模块的问题

问题根源

你的项目中,TypeScript编译器能正常识别模块导入和路径映射,但Jest默认不会读取tsconfig.json的paths配置,同时测试文件里的相对路径也存在错误,导致模块解析失败。

分步解决方案

1. 安装依赖

先安装ts-jest和@types/jest,让Jest适配TypeScript的模块解析规则:

npm install --save-dev ts-jest @types/jest

2. 配置Jest

在项目根目录创建jest.config.cjs文件,内容如下:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src', '<rootDir>/test'],
  // 对应tsconfig里的路径别名
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  moduleFileExtensions: ['ts', 'js', 'json', 'node'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest'
  }
};

3. 修正测试文件的导入路径

当前测试文件里的import { sum } from "./index"路径错误,因为test/index.spec.ts要导入的是src/index.ts,正确相对路径应为:

// index.spec.ts
import { describe, expect, test } from "@jest/globals";
import { sum } from "../src/index";

或者用tsconfig里的别名导入(需要配合上面的Jest配置):

import { sum } from "@/index";

4. 运行测试

执行测试命令验证:

npx jest

若之前缓存有残留,可先清除:

npx jest --clearCache

补充说明

  • 保留原有的babel.config.cjs即可,ts-jest会结合TypeScript配置完成转译,比单纯依赖Babel更适配Jest场景
  • 确保tsconfig.json的baseUrl和paths与Jest的moduleNameMapper完全对应

内容的提问来源于stack exchange,提问作者Shivang Mangal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 21:55:21