Node.js应用中使用ts-jest导入JSON文件时出现报错问题
解决Jest/ts-jest测试中JSON导入assert语句报错的方案
以下是几个可尝试的配置调整方案,按优先级排序:
1. 强制ts-jest使用项目的tsconfig配置
Jest有时会默认读取单独的测试配置文件(比如tsconfig.test.json),如果该文件未设置module: ESNext就会触发报错。你可以在jest.config.js里明确指定使用项目根目录的tsconfig.json:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', globals: { 'ts-jest': { tsconfig: './tsconfig.json' } } };
如果项目有专门的测试用tsconfig文件,记得在该文件中同步设置"module": "ESNext"。
2. 直接在jest配置中覆盖compilerOptions
如果指定tsconfig后问题依旧,可以在jest配置里强制设置module选项,绕过可能的配置读取异常:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', globals: { 'ts-jest': { compilerOptions: { module: 'ESNext' } } } };
3. 改用TypeScript的resolveJsonModule绕过assert语句
你可以不用assert {type: json}语法,只要在tsconfig.json里开启resolveJsonModule: true,就能直接导入JSON文件:
// tsconfig.json { "compilerOptions": { "module": "ESNext", "resolveJsonModule": true, // 其他原有配置... } }
然后导入语句简化为:
import config from './config.json';
这种方式TypeScript会自动处理类型,同时Node.js在ES模块模式下也能正常识别(需确保package.json里有"type": "module")。
4. 适配ES模块的Jest配置
如果你的项目是ES模块(package.json里有"type": "module"),需要调整jest配置来支持ES模块语法:
module.exports = { preset: 'ts-jest/presets/default-esm', testEnvironment: 'node', globals: { 'ts-jest': { useESM: true, tsconfig: './tsconfig.json' } }, // 处理ES模块的路径映射 moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' } };
5. 升级依赖版本
旧版本的ts-jest或Jest对ES模块的assert导入支持不完善,尝试升级到最新稳定版:
npm install --save-dev jest@latest ts-jest@latest typescript@latest
内容的提问来源于stack exchange,提问作者Akash Gorai
相关产品推荐
相关产品推荐

