You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用assert {type:'json'}导入JSON文件时Jest运行崩溃求助

问题:使用assert { type: 'json' }导入JSON时Jest执行测试报错TS2821

执行npm run test时,代码中通过assert { type: 'json' }语法导入JSON文件导致Jest崩溃,抛出TS2821编译错误。

Jest配置

import type { Config } from 'jest'

const config: Config = {
  testEnvironment: 'node',
  transform: {
    '^.+\\.ts$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
  },
  moduleFileExtensions: ['ts', 'js'],
  transformIgnorePatterns: ['/node_modules/'],
  extensionsToTreatAsEsm: ['.ts'],
}

export default config

TypeScript配置(tsconfig.json)

{
  "compilerOptions": {
    "target": "es2021",
    "module": "ESNext",
    "rootDir": "./src",
    "moduleResolution": "Node10",
    "baseUrl": "./src",
    "paths": {
      "*": ["*", "src/*"]
    },
    "resolveJsonModule": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "useUnknownInCatchVariables": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitReturns": false,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts", "src/utils/excelGenerator.ts", "src/__tests__/app.test.ts"],
  "files": ["src/types.d.ts"]
}

报错日志

src/app.ts:6:50 - error TS2821: 仅当'--module'选项设置为'esnext'、'nodenext'或'preserve'时,才支持导入断言。
6 import swaggerFile from '../swagger-output.json' assert { type: 'json' };

Test Suites: 2 failed, 2 total Tests: 0 total Snapshots: 0 total Time: 3.366 s Ran all test suites.

解决方案

1. 统一TypeScript模块解析策略

你的tsconfig.json中module设为ESNext,但moduleResolution用了Node10,两者不匹配导致导入断言无法被识别。将moduleResolution改为NodeNext:

"moduleResolution": "NodeNext"

该配置会让TypeScript按照Node.js的ES模块规则解析文件,和ESNext模块系统兼容,支持导入断言语法。

2. 调整Jest配置适配ES模块

修改Jest配置文件,确保ts-jest正确读取TypeScript配置并处理ES模块:

import type { Config } from 'jest'

const config: Config = {
  testEnvironment: 'node',
  transform: {
    '^.+\\.ts$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
  },
  moduleFileExtensions: ['ts', 'js'],
  transformIgnorePatterns: ['/node_modules/'],
  extensionsToTreatAsEsm: ['.ts'],
  // 新增配置
  globals: {
    'ts-jest': {
      useESM: true,
      tsconfig: './tsconfig.json'
    }
  },
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1'
  }
}

export default config
  • globals指定ts-jest启用ES模块模式,并读取项目根目录的tsconfig。
  • moduleNameMapper处理ES模块导入时的.js后缀问题,避免Jest路径解析失败。

3. 替代方案:移除导入断言

如果不需要严格的类型断言验证,且已经开启resolveJsonModule: true,可以直接简化导入语法:

import swaggerFile from '../swagger-output.json';

该方式在现有配置下完全可行,且兼容性更好,无需额外调整配置。

内容的提问来源于stack exchange,提问作者Gabriel Braga Estefanski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:44:59