我正在尝试测试 Select component 的 onChange
事件使用react-testing-library 。
我使用 getByTestId
获取元素,效果很好,然后设置元素的值,然后调用 fireEvent.change(select);
但 onChange
永远不会被调用,状态也永远不会更新。
我尝试过使用选择组件本身,也尝试过获取对底层 input
元素的引用,但都不起作用。
有什么解决办法吗?或者这是一个已知问题?
最佳答案
material-ui 的 select 组件使用 mouseDown 事件来触发弹出菜单出现。如果您使用 fireEvent.mouseDown 应该触发弹出窗口,然后您可以在出现的列表框中单击您的选择。请参阅下面的示例。
import React from "react";
import { render, fireEvent, within } from "react-testing-library";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import Typography from "@material-ui/core/Typography";
it('selects the correct option', () => {
const {getByRole} = render(
<>
<Select fullWidth value={selectedTab} onChange={onTabChange}>
<MenuItem value="privacy">Privacy</MenuItem>
<MenuItem value="my-account">My Account</MenuItem>
</Select>
<Typography variant="h1">{/* value set in state */}</Typography>
</>
);
fireEvent.mouseDown(getByRole('button'));
const listbox = within(getByRole('listbox'));
fireEvent.click(listbox.getByText(/my account/i));
expect(getByRole('heading')).toHaveTextContent(/my account/i);
});
关于reactjs - 对 Material UI Select 组件的更改使用react测试库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55184037/