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

如何为Next.js项目的E2E测试单独设置testEnvironment: 'node'配置

解决Next.js中Jest组件测试与E2E测试环境冲突的方案

当然可以针对不同类型的测试单独设置环境,下面是几种最佳配置方式:

方式一:使用Jest多项目配置(推荐)

这种方式把组件测试和E2E测试拆分成两个独立的Jest项目,各自维护配置,隔离性最好,也方便单独运行某一类测试。

在项目根目录创建jest.config.js,配置内容如下:

module.exports = {
  projects: [
    // 组件测试专属配置
    {
      displayName: 'components',
      testMatch: ['<rootDir>/src/tests/components/**/*.test.tsx'],
      testEnvironment: 'jsdom',
      // 可添加组件测试需要的其他配置,比如模块映射、转译规则等
    },
    // E2E测试专属配置
    {
      displayName: 'e2e',
      testMatch: ['<rootDir>/src/tests/end-to-end/**/*.test.tsx'],
      testEnvironment: 'node',
      // 可添加E2E测试需要的其他配置,比如全局启动/销毁脚本等
    }
  ]
};

然后在package.json的scripts里添加测试命令:

{
  "scripts": {
    "test": "jest", // 一次性运行所有测试
    "test:components": "jest --selectProjects components", // 仅运行组件测试
    "test:e2e": "jest --selectProjects e2e" // 仅运行E2E测试
  }
}

方式二:单独创建E2E测试配置文件

如果习惯分开维护配置文件,可以为E2E测试单独写一个配置文件,和组件测试的主配置文件区分开。

  1. 根目录创建jest.e2e.config.js:
module.exports = {
  testMatch: ['<rootDir>/src/tests/end-to-end/**/*.test.tsx'],
  testEnvironment: 'node',
  // E2E测试专属配置
};
  1. 组件测试的主配置文件jest.config.js:
module.exports = {
  testMatch: ['<rootDir>/src/tests/components/**/*.test.tsx'],
  testEnvironment: 'jsdom',
  // 组件测试专属配置
};
  1. 在package.json里配置脚本:
{
  "scripts": {
    "test:components": "jest",
    "test:e2e": "jest --config jest.e2e.config.js",
    "test": "npm run test:components && npm run test:e2e"
  }
}

方式三:通过测试路径动态判断环境

如果不想拆分配置文件,可以在主配置里根据测试文件的路径动态返回对应的测试环境,但这种方式的隔离性不如前两种,适合配置差异较小的场景。

jest.config.js内容:

module.exports = {
  testMatch: ['<rootDir>/src/tests/**/*.test.tsx'],
  testEnvironment: (testPath) => {
    // 根据路径判断,包含end-to-end的文件用node环境,否则用jsdom
    return testPath.includes('end-to-end') ? 'node' : 'jsdom';
  },
  // 通用配置
};

推荐优先使用方式一,因为它的配置结构清晰,不同测试类型的配置完全独立,后续扩展或修改某一类测试的配置时不会影响另一类,也方便单独调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:40:01