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

Angular 15项目中npm运行Jest TypeScript测试失败问题

解决Angular 15中npm test未使用ts-jest编译TypeScript测试文件的问题

以下是几个可能的原因及对应的解决办法:

  • npm脚本未调用本地jest实例
    全局安装的jest能正常加载本地项目的ts-jest和配置,但npm运行jest命令时,可能出现依赖加载路径问题,导致无法触发ts-jest预编译。解决方法是在package.json的scripts里明确使用本地jest:

    "scripts": {
      "test": "npx jest --watch"
    }
    

    或者直接指定本地二进制文件路径:

    "scripts": {
      "test": "./node_modules/.bin/jest --watch"
    }
    
  • jest配置文件未被正确加载
    全局执行时可能自动识别了jest.config.js,但npm脚本运行时存在路径偏差,导致配置未生效。可以在脚本里显式指定配置文件:

    "scripts": {
      "test": "jest --watch --config jest.config.js"
    }
    

    同时检查jest.config.js的核心配置是否正确,确保预设和转换器指向ts-jest:

    module.exports = {
      preset: 'jest-preset-angular',
      setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
      transform: {
        '^.+\\.(ts|js|html)$': 'ts-jest'
      }
    };
    
  • 依赖版本不兼容
    Angular 15对jest、ts-jest、jest-preset-angular的版本有严格匹配要求,版本不兼容会导致ts-jest无法正常工作。可以先确认package.json中的依赖版本符合Angular 15的要求(比如jest-preset-angular用v13.x系列),然后删除依赖缓存重新安装:

    rm -rf node_modules package-lock.json
    npm install
    
  • TypeScript配置冲突
    检查tsconfig.spec.json的配置,确保jest能正确解析TypeScript语法:

    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "module": "CommonJS",
        "types": ["jest", "node"]
      },
      "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:57:16