我最近将我的 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