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

使用Next.js搭配Jest运行测试时遭遇环境错误求助

解决Next.js中Jest测试的jsdom环境错误

问题重现

运行Jest测试Next.js项目时,持续出现以下错误:

The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.

已尝试添加文档块指定环境,但无效:

/**
 * @jest-environment jsdom
 */

同时参照Next.js测试文档配置了jest.config.js,无论是否使用Rust编译器方案均无效。相关配置如下:

package.json

{
  "name": "chat",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest --env=node --forceExit --watchAll --coverage"
  },
  "dependencies": {
    "@firebase/testing": "^0.20.11",
    "firebase": "^9.9.4",
    "kill-port": "^2.0.1",
    "next": "12.2.5",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-firebase-hooks": "^5.0.3",
    "react-hot-toast": "^2.3.0",
    "uuid": "^8.3.2"
  },
  "devDependencies": {
    "@babel/plugin-syntax-jsx": "^7.18.6",
    "@babel/preset-react": "^7.18.6",
    "@firebase/rules-unit-testing": "^2.0.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@types/jest": "^29.0.2",
    "eslint": "8.23.0",
    "eslint-config-next": "12.2.5",
    "firebase-admin": "^11.0.1",
    "jest": "^29.0.3",
    "jest-environment-jsdom": "^29.0.3"
  }
}

jest.config.js

// jest.config.js
const nextJest = require('next/jest');

const createJestConfig = nextJest({
    // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
    dir: './',
});

// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const customJestConfig = {
    // Add more setup options before each test is run
    // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
    // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
    //moduleDirectories: ['node_modules', '<rootDir>/'],
    testEnvironment: 'jest-environment-jsdom',
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);

测试文件 test/page.test.js

import { render, screen } from '@testing-library/react';
import Home from '../pages/index';

describe('Home', () => {
    it('renders a heading', () => {
        render(<Home />);
        expect(2 + 2).toBe(4);
    });
}); 

解决方案

1. 移除test脚本中的--env=node参数

你的package.json里的test命令显式指定了--env=node,这会直接覆盖jest.config.js中设置的testEnvironment: 'jest-environment-jsdom',导致配置无效。修改test脚本:

"test": "jest --forceExit --watchAll --coverage"

2. 清除Jest缓存(可选)

如果修改后仍有问题,清除Jest缓存确保配置生效:

npx jest --clearCache

3. 验证环境配置(可选)

可以在测试文件中添加一行代码验证当前环境:

console.log('Test environment:', process.env.JEST_WORKER_ID ? 'jsdom' : 'node');

运行测试后如果输出Test environment: jsdom,说明环境配置正确。

验证修改

修改后重新运行测试,应该可以正常执行,不会再出现环境错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:50:30