我正在使用 React 框架开发一个 Vite 项目。 我使用 vitest 为我的应用程序编写了一些测试用例,当我运行测试时,我看到以下错误
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.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,
},
});
我尝试了以下选项。
您是否尝试过像这样指定测试
environment
:
export default defineConfig({
test: {
globals: true,
environment: "jsdom",
// ...
},
...
}
您还必须安装
jsdom
作为依赖项。
请参阅这些链接以获取更多信息: