Jest无法识别JSON导入中的assert { type: 'json' }语法如何解决?
问题描述
我用TypeScript开发的项目业务代码运行正常,但编写Jest测试用例时,导入JSON文件的语句import xx from '../src/configs/xx.json' assert { type: 'json' }报错,Jest无法识别该assert语法。这种导入方式能让TypeScript自动推导JSON的类型,对开发很有帮助。我尝试过更换TypeScript版本、调整tsconfig.json的module与target配置、更换Jest预设等方法,问题仍未解决。
相关配置如下:
package.json
... "type": "module", "devDependencies": { "@babel/plugin-syntax-import-assertions": "^7.20.0", "@types/jest": "^29.5.0", "@types/node": "^18.15.3", "jest": "^29.5.0", "ts-jest": "^29.0.5", "ts-node": "^10.9.1" }, "dependencies": { "@babel/preset-env": "^7.20.2", "@babel/preset-typescript": "^7.21.0", "big-number": "^2.0.0", "ethers": "5", "icon-sdk-js": "^1.3.0", "typescript": "4.9", "ws": "^8.13.0" }
tsconfig.json
{ "compilerOptions": { "module": "NodeNext", "moduleResolution": "nodenext", "target": "ES2015", "sourceMap": true, "outDir": "dist", "resolveJsonModule": true, "esModuleInterop": true, "types": ["jest"] }, "include": ["src/**/*", "tests/*"] }
babel.config.json
{ "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ], "@babel/preset-typescript" ], "plugins": [ "@babel/plugin-syntax-import-assertions" ] }
jest.config.ts
import { type JestConfigWithTsJest } from "ts-jest"; const jestConfig: JestConfigWithTsJest = { preset: "ts-jest/presets/default-esm", // or other ESM presets moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", }, transform: { "^.+\\.tsx?$": [ "ts-jest", { useESM: true, }, ], }, }; export default jestConfig;
解决方案
方案1:替换为转译插件处理导入断言
你当前使用的@babel/plugin-syntax-import-assertions仅能让Babel解析导入断言的语法,不会将其转译为Jest可识别的代码。需要替换为具备转译能力的插件:
- 安装转译插件:
npm install babel-plugin-transform-import-assertions --save-dev
- 修改
babel.config.json中的插件配置:
{ "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ], "@babel/preset-typescript" ], "plugins": [ "babel-plugin-transform-import-assertions" ] }
该插件会将导入断言语法转译为Jest兼容的形式,同时保留TypeScript的自动类型推导能力。
方案2:配置ts-jest直接处理JSON文件
如果方案1无效,可调整Jest配置,让ts-jest接管JSON文件的转换逻辑:
更新jest.config.ts配置:
import { type JestConfigWithTsJest } from "ts-jest"; const jestConfig: JestConfigWithTsJest = { preset: "ts-jest/presets/default-esm", moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", "^(\\.{1,2}/.*)\\.json$": "$1" // 添加JSON文件路径映射 }, transform: { "^.+\\.tsx?$": [ "ts-jest", { useESM: true, tsconfig: "tsconfig.json" } ], "^.+\\.json$": "ts-jest" // 让ts-jest处理JSON文件转换 }, extensionsToTreatAsEsm: [".ts", ".json"] // 标记JSON为ES模块 }; export default jestConfig;
方案3:临时替代方案(保留类型推导)
如果上述方案无法快速生效,可暂时改用动态导入方式,同时保留类型推导:
// 原代码 // import xx from '../src/configs/xx.json' assert { type: 'json' } // 替换为(测试函数需改为async) const { default: xx } = await import('../src/configs/xx.json', { assert: { type: 'json' } });
内容的提问来源于stack exchange,提问作者vivek sharmapoudel
相关产品推荐
相关产品推荐

