Material UI + React 测试库:单元测试 Select MenuItem 在升级到版本 4 后中断

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

我使用 Jest 和 React 测试库进行了单元测试,可以填写并提交表单。问题是在将 Material UI 升级到版本 4 后,我的单元测试无法 select 一个选项。错误是:"Unable to find an element with the text: Brazil" 巴西是我尝试 select 的文本选项。使用 Material UI 版本 3 工作正常。


测试代码 - 给出错误:"Unable to find an element with the text: Brazil."


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

React 组件代码


<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>

对于 v4,Select 已更改为在 mouseDown 打开,而不是 click (https://github.com/mui-org/material-ui/pull/17978)。

所以代替:

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

你应该有:

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