【问题标题】:MaterialUI + React Testing Library: Unit test Select MenuItem breaks after upgrading to version 4Material UI + React 测试库:升级到版本 4 后单元测试选择菜单项中断
【发布时间】:2020-04-21 08:21:41
【问题描述】:

我有一个使用 Jest 和 React 测试库的单元测试,它填写并提交了一个表单。问题是在将 Material UI 升级到版本 4 后,我的单元测试无法选择一个选项。错误是:“无法找到带有文本的元素:巴西”巴西是我要选择的文本选项。使用 Material UI 版本 3 运行良好。


测试代码 - 给出错误:“无法找到带有文本的元素:巴西。”


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>

【问题讨论】:

    标签: reactjs jestjs material-ui react-testing-library


    【解决方案1】:

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

    所以而不是:

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

    你应该有:

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

    【讨论】:

    • 我已经找了好几个小时了!!谢谢
    猜你喜欢
    • 2018-02-09
    • 2020-04-26
    • 2019-08-10
    • 2018-01-12
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多