NodeJS TypeScript中Jest测试报错:Cannot use import statement outside a module
解决Jest测试中"SyntaxError: Cannot use import statement outside a module"的问题
问题根源
项目同时启用ES模块(package.json里的"type":"module")和TypeScript,但Jest默认对ES模块的支持需要额外配置,加上你使用的Jest版本(26.x)较旧,需要适配TS与ES模块的编译逻辑。
具体修复步骤
1. 安装Jest TypeScript处理器
Jest本身无法直接编译TypeScript,需安装ts-jest及相关依赖:
npm install --save-dev ts-jest @types/node
2. 创建Jest配置文件
在项目根目录新建jest.config.js(采用CommonJS格式适配Jest 26版本):
module.exports = { preset: 'ts-jest', testEnvironment: 'node', moduleFileExtensions: ['ts', 'js'], transform: { '^.+\\.tsx?$': 'ts-jest', }, testMatch: ['**/tests/**/*.ts'], globals: { 'ts-jest': { tsconfig: 'tsconfig.json', }, }, };
3. 调整测试脚本
修改package.json中的test脚本,指定Jest配置文件:
"scripts": { "test": "jest --verbose --config jest.config.js ./tests" }
4. 修复测试文件语法错误
你的测试代码存在语法问题:expect(add1(2,3).toBe(5); 缺少一个右括号,修正为:
import { add1 } from "../functions/add" it('simple test',()=>{ expect(add1(2,3)).toBe(5); })
5. 优化TypeScript配置
在tsconfig.json的compilerOptions中添加模块解析规则,确保ES模块与CommonJS兼容:
{ "compilerOptions": { // 保留原有配置 "moduleResolution": "node" } }
验证修复
运行测试命令验证效果:
npm run test
此时Jest会通过ts-jest编译TypeScript文件,正常处理ES模块导入语法,测试可顺利执行。
内容的提问来源于stack exchange,提问作者sidharth sunilkumar
相关产品推荐
相关产品推荐

