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

升级Angular 17后单元测试失败问题求助

Angular 15 升级至 17 后 Jest 测试错误解决方案
  • 同步 Jest 及依赖版本
    Angular 17 对 Jest 版本有明确兼容要求,先卸载旧版本再安装适配包:

    npm uninstall jest @types/jest jest-preset-angular
    npm install jest@^29.7.0 @types/jest@^29.5.12 jest-preset-angular@^14.0.3 --save-dev
    

    版本号可根据 Angular 17 官方文档调整,确保完全兼容。

  • 更新 Jest 配置文件
    修改项目根目录的 jest.config.js,配置项需匹配 Angular 17 环境:

    module.exports = {
      preset: 'jest-preset-angular',
      setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
      transform: {
        '^.+\\.(ts|js|html)$': 'jest-preset-angular',
      },
      testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/'],
      moduleFileExtensions: ['ts', 'html', 'js', 'json'],
      globals: {
        'ts-jest': {
          tsconfig: '<rootDir>/tsconfig.spec.json',
          stringifyContentPathRegex: '\\.html$',
        },
      },
    };
    
  • 调整测试初始化文件
    确保 setup-jest.ts 中正确引入初始化代码:

    import 'jest-preset-angular/setup-jest';
    
  • 修正组件测试逻辑
    Angular 17 对异步测试的处理更严格,若测试中存在异步操作:

    • 替换 fakeAsync 中真实的 HTTP 请求为模拟数据(如 HttpClientTestingModule)
    • 组件初始化后需调用 await fixture.whenStable() 确保异步逻辑完成
  • 检查 TypeScript 测试配置
    修改 tsconfig.spec.json 的编译选项:

    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "target": "ES2022",
        "module": "ES2022",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "types": ["jest"]
      },
      "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
    }
    
  • 清理缓存重新执行测试

    npx jest --clearCache
    npm run test
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:39:59