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

在Nx Monorepo的Angular库中配置Jest测试报错求助

Nx Monorepo中Angular库Jest配置报错问题

项目结构

apps/
libs/
 - angular/
  |- projects/
    |- angular-components/
      |- src/
        |- lib/
          |- componentA/
        |- tests/  
    package.json
    tsconfig.lib.json
    tsconfig.spec.json 
  angular.json
  package.json
  jest.config.ts
  setup-jest.ts
  tsconfig.json
  tsconfig.spec.json 
 - react
..
jest.config.ts
package.json

报错信息

在IntelliJ IDEA中运行测试时出现以下错误:

Error: Jest: Failed to parse the TypeScript config file /Users/user/Desktop/my-nx-project/libs/angular/jest.config.ts
  TSError: ⨯ Unable to compile TypeScript:
jest.config.ts(6,27): error TS2306: File '/Users/user/Desktop/my-nx-project/libs/angular/node_modules/@types/jest/index.d.ts' is not a module.

当前jest.config.ts配置

import type { Config } from 'jest';

const config: Config = {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8",
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': 'ts-jest',
  },
  verbose: true,
};

export default config;

解决建议

  • 统一安装依赖:在项目根目录执行命令,确保Jest相关依赖统一安装,避免子目录版本冲突:
    npm install --save-dev jest jest-preset-angular ts-jest @types/jest
    
  • 修正TypeScript配置:修改libs/angular/tsconfig.json,确保compilerOptions中包含jest类型:
    {
      "compilerOptions": {
        "types": ["jest", "node"],
        "moduleResolution": "node"
      }
    }
    
  • 调整类型导入路径:若仍报错,将配置文件中的类型导入替换为:
    import type { Config } from '@jest/types';
    
  • 清理缓存:执行命令清除Jest和TypeScript缓存后重试:
    npx jest --clearCache
    rm -rf node_modules/.cache
    
  • 刷新IDE缓存:关闭并重新打开IntelliJ IDEA,确保IDE读取最新的依赖和配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:20:28