我最近将我的 React 项目升级到了 ant design v4,所有使用 Select、AutoComplete 或 Tooltip 的测试都被破坏了。基本上,当单击组件时,JSDOM 中不存在模式或选择选项。这曾经在 v3 中运行良好。
有人可以告诉我如何使用 react 测试库测试 antd v4 吗?
示例:
我的组件:
import React from "react";
import "./styles.css";
import { Select } from "antd";
const { Option } = Select;
function handleChange(value) {
console.log(`selected ${value}`);
}
export default function App() {
return (
<div className="App" style={{ marginTop: "40px" }}>
<Select
defaultValue="lucy"
style={{ width: 120 }}
onChange={handleChange}
>
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="disabled" disabled>
Disabled
</Option>
<Option value="Yiminghe">yiminghe</Option>
</Select>
</div>
);
}
我的测试
import "@testing-library/jest-dom/extend-expect";
import React from "react";
import { render, fireEvent, prettyDOM } from "@testing-library/react";
import App from "./App";
test("App Test", () => {
const { queryAllByText, getByText, container } = render(<App />);
expect(queryAllByText("Lucy").length).toBe(1);
expect(queryAllByText("Jack").length).toBe(0);
fireEvent.click(getByText("Lucy"));
console.log(prettyDOM(container));
// This line fails although I would expect the dropdown to be open and all the options visible
expect(queryAllByText("Jack").length).toBe(1);
});
这是重现该问题的代码框的链接。 (如前所述,该代码曾经在 v3 中工作)。
https://codesandbox.io/s/staging-shape-0xkrl?file=/src/App.test.js:0-494
最佳答案
在此失去 2 天后,这里是问题和解决方案:
问题
在 antd v3 中,以前可以通过执行 selectHtmlElement.click()
来打开 Select。 .您可以在 chrome 开发工具控制台中进行测试。在 v4 中,这不起作用。
这意味着在后台使用 JSDOM 的 RTL 将具有相同的行为。当你这样做 fireEvent.click(selectElement);
什么都没发生 !
解决方案
这让我走上了正轨:https://github.com/ant-design/ant-design/issues/22074
您需要触发的事件不是 click()
但是一个 mouseDown()
在选择的第一个 child 上。
const elt = getByTestId('your-select-test-id').firstElementChild;
fireEvent.mouseDown(elt); // THIS WILL OPEN THE SELECT !
现在此时您可能想从列表中选择一个选项,但有一个动画正在进行,因此以下代码(曾经在 v3 中工作)也将失败。
expect(getByText('Option from Select')).toBeVisible(); // FAILS !
您有 2 个选项,请使用
toBeInTheDocument()
或使用 waitFor(...)
等待动画结束选项 1:更快但不完全准确,我更喜欢将其用于简单的用例,因为它使测试更快且同步
expect(getByText('Option from Select')).toBeInTheDocument(); // WORKS !
选项 2:因为您需要等待动画完成而更慢,但对于复杂情况更准确
await waitFor(() => expect(getByText('Option from Select')).toBeVisible()); // WORKS !
关于javascript - ant design v4 打破了对 Select 和 Autocomplete 的 react 测试库测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61080116/