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

Next.js项目中Jest测试React组件遇document未定义错误

解决Next.js中Jest测试React组件时document is not defined的错误

问题场景

在Next.js项目中使用Jest和React Testing Library编写单元测试,测试逻辑是渲染带'use client'指令的Home组件并检查是否存在“Home”文本,运行测试时抛出以下错误:

Testing Home Component › renders a heading

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.

ReferenceError: document is not defined

测试代码(Home.test.tsx):

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

describe("Testing Home Component", () => {
  it("renders a heading", () => {
    render(<Home />);
    const text = screen.getByText(/Home/i);
    expect(text).toBeInTheDocument();
  });
});

Home组件代码(Home.tsx):

'use client'

import React from 'react'

const Home = () => {
  return (
    <div>
      Home
    </div>
  )
}

export default Home

问题原因

Jest默认使用Node.js环境运行测试,而Node环境中不存在浏览器的document等DOM API。React组件渲染依赖这些DOM API,因此需要切换到jsdom环境——它是一个模拟浏览器DOM的库,能让Jest在Node环境中模拟浏览器行为。

解决方案

1. 安装必要依赖

首先确保安装jest-environment-jsdom及相关类型(TypeScript项目需要):

npm install --save-dev jest-environment-jsdom @types/jest @types/jsdom

2. 配置Jest测试环境

在项目的jest.config.js(或jest.config.ts)文件中,将testEnvironment设置为'jsdom':

/** @type {import('jest').Config} */
const jestConfig = {
  testEnvironment: 'jsdom',
  // 其他Jest配置(比如模块映射、测试文件匹配规则等)
};

module.exports = jestConfig;

如果是使用Next.js官方提供的Jest配置模板,可直接在Jest配置文件中继承Next的基础配置,确保testEnvironment覆盖为jsdom即可。

3. 重新运行测试

执行测试命令(比如npm test),此时测试应该能正常渲染组件并通过断言。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:52:07