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

Nx Monorepo中Jest配置一致却仅单个项目测试失败求助

Monorepo添加全局Jest Setup文件后单个项目测试失败排查

问题背景

我的Monorepo中每个项目都有独立的jest.config.ts文件,此前所有测试均能正常通过。但添加全局setup文件后,除一个项目外其余测试均正常运行,且该失败项目的配置文件与某一正常项目完全一致。


正常项目的jest.config.ts配置

export default {
  displayName: 'server-maintain-products',
  preset: '../../../jest.preset.js',
  testEnvironment: 'node',
  transform: {
    '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
  },
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../../coverage/libs/server/maintain-products',
};

失败项目的jest.config.ts配置

export default {
  displayName: 'shared-data',
  preset: '../../../jest.preset.js',
  testEnvironment: 'node',
  transform: {
    '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
  },
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../../coverage/libs/shared/data',
};

全局配置文件

jest.preset.js

const nxPreset = require('@nx/jest/preset').default;

module.exports = {
  ...nxPreset,
  /* TODO: Update to latest Jest snapshotFormat
   * By default Nx has kept the older style of Jest Snapshot formats
   * to prevent breaking of any existing tests with snapshots.
   * It's recommend you update to the latest format.
   * You can do this by removing snapshotFormat property
   * and running tests with --update-snapshot flag.
   * Example: "nx affected --targets=test --update-snapshot"
   */
  snapshotFormat: { escapeString: true, printBasicPrototype: true },
  setupFiles: ['./jest.setup.ts'],
};

jest.setup.ts

import { registerTsProject } from '@nx/js/src/internal';
const cleanupRegisteredPaths = registerTsProject('./tsconfig.base.json');

export default async function () {
  // make sure to run the clean up!
  cleanupRegisteredPaths();
}

报错内容

Error: ● Validation Error:

  Module ./jest.setup.ts in the setupFiles option was not found.
         <rootDir> is: C:\path\to\dir\libs\shared\data

  Configuration Documentation:
  https://jestjs.io/docs/configuration

问题原因

从报错信息可以明确:Jest在失败项目的根目录(C:\path\to\dir\libs\shared\data)下查找./jest.setup.ts,但该文件实际位于Monorepo根目录,而非项目目录。

其他项目能正常运行的核心原因是:它们的目录层级导致../../../jest.preset.js加载后,preset中的相对路径./jest.setup.ts恰好能解析到Monorepo根目录;而失败项目的层级使得Jest将preset中的路径解析为相对于项目自身的rootDir,而非preset文件所在的Monorepo根目录。


解决方法

方法1:在preset中使用绝对路径(推荐)

修改jest.preset.js,通过__dirname(当前preset文件所在目录,即Monorepo根目录)来定位setup文件,避免相对路径解析错误:

// jest.preset.js
const path = require('path');
const nxPreset = require('@nx/jest/preset').default;

module.exports = {
  ...nxPreset,
  snapshotFormat: { escapeString: true, printBasicPrototype: true },
  setupFiles: [path.resolve(__dirname, './jest.setup.ts')],
};

方法2:给失败项目显式指定rootDir

在失败项目的jest.config.ts中添加rootDir配置,指向Monorepo根目录,同时同步调整tsconfig的路径:

export default {
  displayName: 'shared-data',
  rootDir: '../../../../', // 根据项目层级调整到Monorepo根目录
  preset: '../../../jest.preset.js',
  testEnvironment: 'node',
  transform: {
    '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/libs/shared/data/tsconfig.spec.json' }],
  },
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../../coverage/libs/shared/data',
};

方法3:使用Nx官方全局Setup配置

利用Nx内置的全局配置能力,在nx.json中统一配置测试的setup文件,避免手动处理路径问题:

// nx.json
{
  "targetDefaults": {
    "test": {
      "options": {
        "setupFiles": ["<rootDir>/jest.setup.ts"]
      }
    }
  }
}

之后可以移除jest.preset.js中的setupFiles配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:44:53