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

Angular 17复杂组件Jest测试ESM导入问题排查

解决Angular 17迁移Jest后复杂组件测试的ESM加载错误

将Angular 17项目从Karma迁移至Jest时,基础组件测试正常,但测试包含Angular Material、自定义服务等多依赖的复杂组件时,出现ESM模块加载错误:Must use import to load ES Module: /myrepo/node_modules/@angular/core/fesm2022/core.mjs。结合你的环境及已尝试操作,可按以下步骤排查修复:

1. 修正Jest配置文件的ESM相关设置

确保jest.config.js启用ESM模式并正确处理Angular依赖:

export default {
  preset: 'jest-preset-angular/presets/default-esm',
  extensionsToTreatAsEsm: ['.ts'],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    '^.+\\.(ts|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: [
    'node_modules/(?!@angular|@angular/material|@angular/cdk|rxjs)'
  ],
  globals: {
    'ts-jest': {
      useESM: true,
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$',
    },
  },
};

2. 校验测试专用TS配置

确保tsconfig.spec.json启用ESM编译选项:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES2022",
    "esModuleInterop": true,
    "moduleResolution": "bundler",
    "types": ["jest"]
  },
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

3. 调整package.json的模块类型

在项目根目录的package.json中添加模块类型声明:

{
  "type": "module"
}

同时更新测试命令,启用Node的ESM支持参数:

{
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  }
}

4. 重置依赖与缓存

执行以下命令清理缓存并重新安装依赖:

rm -rf node_modules package-lock.json
npm install
npx jest --clearCache

5. 规范测试文件的导入语法

确保测试文件使用ESM风格导入,避免CommonJS的require语法:

// 正确写法
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComplexComponent } from './my-complex.component';

// 错误写法(需避免)
const { ComponentFixture } = require('@angular/core/testing');

环境信息参考:

  • Angular: 17.3.8
  • jest-preset-angular: ^14.4.2
  • jest: ^29.7.0
  • Node: 18.19.0

内容的提问来源于stack exchange,提问作者Stephen Carroll

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 01:30:00