我目前正在尝试模拟react-select组件,无论我做什么,react-testing-library中的firevent.change似乎只会在第一次调用firevent.change时触发。
我想知道为什么更改只触发一次以及如何修复它。
我的 Jest 模拟如下:
jest.mock("react-select", () => ({ options, value, onChange }) => {
function handleChange(event) {
console.log("called");
const option = options.find(option => {
return option.value == event.currentTarget.value;
});
onChange(option);
}
return (
<select
id="uc"
data-testid="select"
value={value}
onChange={event => handleChange(event)}
>
{options?.map(({ label, value }) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
);
});
正如您所看到的,它是一个相当简单的选择 block ,我认为我应该能够调用。
fireEvent.change(selectOptions[0], { target: { value: "0"} });
但是,如果我将它们链接在一起,如下例所示,这将起作用:
test("Should render add another button and function", () => {
const mockSetOpen = jest.fn();
const { queryAllByTestId, getByTestId, getByLabelText, debug } = renderWithRedux(
<TabByRestraints setOpen={mockSetOpen} hidden={false} />,
{
userCatagories: userCategoriesMock,
permissionGroups: permissionGroupsMock,
roles: rolesMock
}
);
// Check that the user catagories exist and user catagories values
const selectOptions = queryAllByTestId("select");
expect(selectOptions).toHaveLength(2);
expect(getByTestId("user-category-row")).toBeTruthy();
fireEvent.change(selectOptions[0], { target: { value: "0" } });
fireEvent.change(selectOptions[1], { target: { value: "132" } });
expect(getByLabelText("Add a new user category restraint")).toBeTruthy();
});
我可以看到 console.log("used") 仅被触发一次。页面上的第二个选择永远不会选择其值,因此测试失败。
我希望这两个更改都能调度更改事件。
fireEvent.change(selectOptions[0], { target: { value: "0" } });
fireEvent.change(selectOptions[1], { target: { value: "132" } });
但是它只设置第一个。
非常感谢任何帮助。
请您参考如下方法:
您应该对选择的元素执行另一个查询。我会更进一步,以不同的方式命名它们,以使测试更易于阅读/调试。
// it's easier to have separate ids for each select, will be easier to read/maintain the test in the future
const firstSelect = queryByTestId("select1");
fireEvent.change(firstSelect, { target: { value: "0" } });
// a rerender might have happened so you need to query for the second select after the first event.
const secondSelect = queryByTestId("select2");
fireEvent.change(secondSelect, { target: { value: "132" } });
expect(getByLabelText("Add a new user category restraint")).toBeTruthy();






