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

NestJS应用中Jest无法识别绝对路径的解决求助

解决NestJS测试与构建时的模块路径问题

问题分析

你遇到两类路径错误:

  • 测试阶段使用src/开头的绝对路径时,无法找到对应模块
  • 改为相对路径后,构建产物运行时仍提示找不到模块
    核心原因是TypeScript编译路径、Nest构建配置与Jest测试配置未统一匹配。

解决方案

1. 配置TypeScript路径映射

在项目根目录的tsconfig.json中添加baseUrl和paths,让TypeScript识别src/开头的绝对路径:

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "src/*": ["src/*"]
    },
    // 保留原有其他编译配置
  }
}

2. 同步Nest CLI构建配置

修改nest-cli.json,确保编译器使用上述TypeScript配置,保证构建时路径正确转换:

{
  "compilerOptions": {
    "deleteOutDir": true,
    "tsConfigPath": "./tsconfig.json"
  }
}

3. 完善Jest测试配置

单元测试配置(jest.config.ts)

确保moduleNameMapper正确映射路径,同时配置编译规则:

export default {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: '.',
  testRegex: '.*\\.spec\\.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src/$1',
  },
  collectCoverageFrom: ['**/*.(t|j)s'],
  coverageDirectory: '../coverage',
  testEnvironment: 'node',
};

E2E测试配置(jest-e2e.config.ts)

E2E测试目录通常在test下,需调整路径映射指向上层的src目录:

export default {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: '.',
  testEnvironment: 'node',
  testRegex: '.e2e-spec.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/../src/$1',
  },
};

4. 重新构建项目

清理旧构建文件并重新编译,避免旧产物干扰:

rm -rf dist && npm run build

完成以上配置后,无论是运行单元测试、E2E测试还是启动后端服务,路径问题都应该能解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:50:13