如何在TypeScript+Node.js环境下为Jest测试导入ES2020函数
Jest + TypeScript 测试报错修复方案
问题1:dist目录测试文件出现SyntaxError: Cannot use import statement outside a module
原因
Jest默认优先处理CommonJS模块,但项目通过package.json的"type": "module"启用了ES模块,同时Jest扫描到了dist目录下编译后的ES模块格式测试文件,导致解析冲突。
修复步骤
修改jest.config.js,限定测试文件范围并启用ESM兼容
配置Jest只处理原TS测试文件,忽略编译后的dist目录,同时让ts-jest适配ES模块:/** @type {import('ts-jest').JestConfigWithTsJest} */ export default { preset: 'ts-jest', testEnvironment: 'node', testMatch: ['<rootDir>/tests/**/*.test.ts'], modulePathIgnorePatterns: ['<rootDir>/dist/'], transform: { '^.+\\.tsx?$': ['ts-jest', { useESM: true }] } };保持package.json的ES模块配置
无需修改"type": "module",该配置是项目ES模块模式的基础,需与Jest配置匹配。
问题2:TS1343 import.meta.url 语法错误
原因
当前tsconfig.json的模块解析模式与import.meta.url的语法要求不匹配,moduleResolution设置为node无法正确识别Node.js ES模块特有的元属性。
修复步骤
更新tsconfig.json的模块相关配置,适配Node.js ES模块规范:
{ "compilerOptions": { "target": "es2022", "module": "nodenext", "moduleResolution": "nodenext", "outDir": "dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "sourceMap": true } }
如果misc.ts中import.meta.url是误添加的代码,直接删除相关行也可解决该报错。
验证修复
执行npm run test,此时Jest会仅处理tests目录下的TS文件,通过ts-jest完成ES模块兼容转译,同时TypeScript语法检查可正常识别import.meta.url。
内容的提问来源于stack exchange,提问作者swftowu69
相关产品推荐
相关产品推荐

