Cod*_*ity 5 reactjs react-testing-library vitest
当使用开箱即用的 Create React App 时,以下测试运行并通过得很好。
\nimport { 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});\nRun Code Online (Sandbox Code Playgroud)\n所以,测试本身应该没问题。是的,只有 1\xef\xb8\x8f\xe2\x83\xa3 按钮,那就是type="submit"。应用程序在浏览器中运行时可以正常工作,并且在 Create React App (CRA) 中测试正常。
我正在尝试迁移到 Vitest(使用 Vite)。理论上,上述测试不需要改变。然而,这就是发生的事情:TypeError: target.ownerDocument.createRange is not a function。
让我们开始配置。
\nvite.config.js看起来像这样:
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});\nRun Code Online (Sandbox Code Playgroud)\n./src/setup.js看起来像这样:import "happy-dom";
是的,我也尝试过jsdom。
我也替换userEvent.click为fireEvent.click. 我还在data-testid我的表单中添加了一个并fireEvent.submit直接在该表单上尝试。
在后一种情况下,没有错误,但未触发表单提交,或者触发了提交,但渲染未更新。
\n事实上,如果 CRA 有效,那么测试就不必改变。可能只有配置。
\n我喜欢 Vite,但如果我无法获得测试 \xe2\x9c\x85 体验,就无法继续使用它。
\n| 归档时间: |
|
| 查看次数: |
2458 次 |
| 最近记录: |