NestJS Jest E2E测试报错:无法找到app.module.js模块
NestJS E2E测试中NodeNext模块解析导致的模块找不到问题
使用NestJS + Jest编写E2E测试时,由于项目启用了NodeNext模块解析(package.json设置"type": "module",tsconfig.json配置"moduleResolution": "NodeNext"),在测试文件中导入AppModule时添加.js扩展名后出现报错:
Cannot find module '../src/app.module.js' from 'app.e2e-spec.ts'
项目主体代码中使用.js扩展名导入.ts文件正常,但测试环境下Jest无法识别这种映射。
问题原因
TypeScript的NodeNext模块解析允许你在导入.ts文件时添加.js扩展名,编译时会自动替换为实际的.js输出文件路径。但Jest在运行E2E测试时,直接处理的是.ts源文件,不会自动将.js扩展名映射到对应的.ts文件,因此会找不到模块。
解决方案
方案1:修改测试文件的导入路径,移除.js扩展名
直接在测试文件中使用.ts文件的原始路径(不带.js扩展名),适配Jest的源文件处理逻辑:
import { Test } from '@nestjs/testing'; import { AppModule } from '../src/app.module'; // 移除.js扩展名 describe('App end2end test', ()=> { beforeAll(async ()=> { const moduleRef = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); }) it.todo('should pass'); })
方案2:配置Jest支持.js到.ts的映射(保留测试文件中的.js扩展名)
如果希望保持测试文件和主体代码的导入风格一致,需要修改jest-e2e.json配置,让Jest自动将.js扩展名映射到对应的.ts源文件:
{ "moduleFileExtensions": ["js", "json", "ts"], "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", "transform": { "^.+\\.(t|j)s$": ["ts-jest", { "useESM": true }] // 启用ES模块支持 }, "extensionsToTreatAsEsm": [".ts"], // 将.ts文件视为ES模块处理 "moduleNameMapper": { "^(\\.{1,2}/.*)\\.js$": "$1" // 把.js扩展名映射到对应的.ts文件 }, "tsconfigRootDir": "./" // 指定tsconfig的根目录,确保Jest读取正确的模块解析规则 }
同时需要更新package.json中的test:e2e命令,添加Node.js处理ES模块的必要参数:
{ "scripts": { "test:e2e": "node --experimental-vm-modules node_modules/jest/bin/jest.js --config ./test/jest-e2e.json" } }
验证修改
完成上述配置调整后,重新运行npm run test:e2e,Jest即可正确解析模块路径,测试可以正常执行。
内容的提问来源于stack exchange,提问作者ShueiYang
相关产品推荐
相关产品推荐

