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

Vite+React项目使用Vitest测试时出现document未定义错误求助

React + Vite + Vitest 测试报错:document is not defined

错误详情

FAIL tests/Reservations.test.jsx > Reservations Component > displays error for invalid number of guests exceeding maximum
ReferenceError: document is not defined
 ❯ Proxy.render node_modules/@testing-library/react/dist/pure.js:215:5
 ❯ tests/Reservations.test.jsx:28:9
     26| 
     27|     it("displays error for invalid number of guests exceeding maximum", () => {
     28|         render(<Reservations />)
       |         ^
     29|         fireEvent.change(screen.getByLabelText(/Number of Guests/i), { target: { value: "15" } })
     30|         fireEvent.click(screen.getByText(/Make your reservation/i))

测试代码

import { Reservations } from "../src/components"
import { render, screen, fireEvent } from "@testing-library/react"
import { expect, describe, it } from "vitest"

describe("Reservations Component", () => {
    it("renders the 'Book Your Table Now' page title", () => {
        render(<Reservations />)
        const pageTitle = screen.getByText(/Book Your Table Now/i)
        expect(pageTitle).toBeInTheDocument()
    })

    it("displays error for missing date when submitting", () => {
        render(<Reservations />)
        fireEvent.click(screen.getByText(/Make your reservation/i))
        const errorMessage = screen.getByText(/Please choose a date/i)
        expect(errorMessage).toBeInTheDocument()
    })

    it("displays error for invalid time outside allowed range", () => {
        render(<Reservations />)
        fireEvent.change(screen.getByLabelText(/Choose Time/i), { target: { value: "14:00" } })
        fireEvent.click(screen.getByText(/Make your reservation/i))
        const errorMessage = screen.getByText(/Please choose a time between 5:00 PM and 10:00 PM/i)
        expect(errorMessage).toBeInTheDocument()
    })

    it("displays error for invalid number of guests exceeding maximum", () => {
        render(<Reservations />)
        fireEvent.change(screen.getByLabelText(/Number of Guests/i), { target: { value: "15" } })
        fireEvent.click(screen.getByText(/Make your reservation/i))
        const errorMessage = screen.getByText(/Please choose a guests between 1 and 10/i)
        expect(errorMessage).toBeInTheDocument()
    })
})

Vite 配置文件 (vite.config.js)

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    include: ["src/**/*.test.js", "tests/**/*.test.js"],
    parallel: true,
  },
});

已尝试的解决方法

  • 删除 node_modules 文件夹后重新安装
  • 反复检查测试环境设置
  • 排查测试代码逻辑
  • 查阅相关技术文档

解决方案

问题核心是 Vitest 默认使用 Node.js 环境运行测试,而 Node.js 中不存在浏览器专属的 document 对象。要测试 React 组件,需要切换到模拟浏览器 DOM 的 jsdom 环境。

步骤1:修改 Vite 测试配置

在 vite.config.js 的 test 配置块中添加 environment: 'jsdom':

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    include: ["src/**/*.test.js", "tests/**/*.test.js"],
    parallel: true,
    // 新增配置:指定测试环境为jsdom
    environment: 'jsdom'
  },
});

步骤2:安装 jsdom 依赖

如果项目中尚未安装 jsdom,执行以下命令安装开发依赖:

npm install -D jsdom
# 或使用 yarn/pnpm
yarn add -D jsdom
pnpm add -D jsdom

完成上述配置后重新运行测试,document is not defined 错误即可解决。

内容的提问来源于stack exchange,提问作者Engr. Umair Ul Isam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:45:02