为什么“userEvent.click”不触发 Vitest 和 React 测试库的表单提交?

Cod*_*ity 5 reactjs react-testing-library vitest

当使用开箱即用的 Create React App 时,以下测试运行并通过得很好。

\n
import { render, screen } from "@testing-library/react";\nimport userEvent from "@testing-library/user-event";\nimport App from "./App";\n\ndescribe("Update the name", () => {\n  it("updates the name", () => {\n    render(<App />);\n    userEvent.type(screen.getByLabelText(/name/i), "John");\n    userEvent.click(screen.getByRole("button"));\n\n    expect(screen.getByText("John")).toBeInTheDocument();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

所以,测试本身应该没问题。是的,只有 1\xef\xb8\x8f\xe2\x83\xa3 按钮,那就是type="submit"。应用程序在浏览器中运行时可以正常工作,并且在 Create React App (CRA) 中测试正常。

\n

我正在尝试迁移到 Vitest(使用 Vite)。理论上,上述测试不需要改变。然而,这就是发生的事情:TypeError: target.ownerDocument.createRange is not a function

\n

让我们开始配置。

\n

vite.config.js看起来像这样:

\n
import { render, screen } from "@testing-library/react";\nimport userEvent from "@testing-library/user-event";\nimport App from "./App";\n\ndescribe("Update the name", () => {\n  it("updates the name", () => {\n    render(<App />);\n    userEvent.type(screen.getByLabelText(/name/i), "John");\n    userEvent.click(screen.getByRole("button"));\n\n    expect(screen.getByText("John")).toBeInTheDocument();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

./src/setup.js看起来像这样:import "happy-dom";

\n

是的,我也尝试过jsdom

\n

我也替换userEvent.clickfireEvent.click. 我还在data-testid我的表单中添加了一个并fireEvent.submit直接在该表单上尝试。

\n

在后一种情况下,没有错误,但未触发表单提交,或者触发了提交,但渲染未更新。

\n

事实上,如果 CRA 有效,那么测试就不必改变。可能只有配置。

\n

我喜欢 Vite,但如果我无法获得测试 \xe2\x9c\x85 体验,就无法继续使用它。

\n