MaterialUI + React Testing Library: Unit test Select MenuItem breaks after upgrading to version 4

南笙酒味 提交于 2020-06-27 12:51:29

问题


I've got a unit test using Jest and React Testing Library that fills and submits a form. The problem is that after upgrading Material UI to version 4 my unit test fails to select an option. The error is: "Unable to find an element with the text: Brazil" Brazil is the text option I'm trying to select. Using Material UI version 3 was working just fine.


Test Code - Gives error: "Unable to find an element with the text: Brazil."


fireEvent.click(getByTestId("id-country"));
const countryOption = await waitForElement(() => getByText("Brazil"));
fireEvent.click(countryOption);

React Component Code


<Grid item xs={12} sm={4}>
        <TextField
            id="select-country"
            name="country"
            select
            helperText={touched.country ? errors.country : ""}
            error={touched.country && Boolean(errors.country)}
            required
            label="Country"
            onChange={handleChange}
            value={values.country}
            className={classes.selectField}
            SelectProps={{
                SelectDisplayProps: {
                    "data-testid": "id-country"
                }
            }}
        >
            {countryEnum.map(country => (
                <MenuItem key={country.type} value={country.type}>
                    {country.label}
                </MenuItem>
            ))}
        </TextField>
</Grid>

回答1:


For v4, the Select was changed to open on mouseDown instead of click (https://github.com/mui-org/material-ui/pull/17978).

So instead of:

fireEvent.click(getByTestId("id-country"));

you should have:

fireEvent.mouseDown(getByTestId("id-country"));


来源:https://stackoverflow.com/questions/59567234/materialui-react-testing-library-unit-test-select-menuitem-breaks-after-upgra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!