NestJS微服务E2E测试时出现Cannot find module '@app/common'错误
解决NestJS E2E测试中无法找到@app/common模块的问题
这个问题本质是Jest在E2E测试环境下无法识别项目中配置的TypeScript路径别名,以下是具体解决步骤:
1. 确认TypeScript路径配置
首先检查项目根目录的tsconfig.json,确保已正确配置@app/common的路径映射:
{ "compilerOptions": { "baseUrl": "./", "paths": { "@app/common": ["libs/common/src"], "@app/common/*": ["libs/common/src/*"] } } }
2. 配置Jest的模块解析规则
Jest不会自动读取tsconfig.json的paths配置,需要在E2E测试的Jest配置文件(通常是test/jest-e2e.json)中添加moduleNameMapper,手动映射路径别名:
{ "moduleFileExtensions": ["js", "json", "ts"], "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "moduleNameMapper": { "^@app/common$": "<rootDir>/libs/common/src", "^@app/common/(.*)$": "<rootDir>/libs/common/src/$1" } }
如果项目使用的是jest.config.js格式的配置,对应的配置代码如下:
module.exports = { moduleFileExtensions: ['js', 'json', 'ts'], rootDir: '.', testEnvironment: 'node', testRegex: '.e2e-spec.ts$', transform: { '^.+\\.(t|j)s$': 'ts-jest' }, moduleNameMapper: { '^@app/common$': '<rootDir>/libs/common/src', '^@app/common/(.*)$': '<rootDir>/libs/common/src/$1' } };
3. 确保公共模块已构建(若为独立Lib)
如果@app/common是通过NestJS CLI生成的独立library,需要先执行构建命令生成编译后的文件,否则Jest无法找到对应的模块:
npm run build common
4. 验证测试脚本配置
检查package.json中的E2E测试脚本,确保它指向正确的Jest配置文件:
{ "scripts": { "test:e2e": "jest --config ./test/jest-e2e.json" } }
内容的提问来源于stack exchange,提问作者morteza mortezaie
相关产品推荐
相关产品推荐

