本文介绍了MaterialUI + React Testing库:单元测试Select MenuItem在升级到版本4后中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Jest和React Testing Library进行了单元测试,可以填写并提交表格.问题是将Material UI升级到版本4后,我的单元测试无法选择一个选项.错误为:无法找到带有文本的元素:巴西"巴西是我要选择的文本选项.使用Material UI版本3可以正常工作.

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>

推荐答案

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

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

所以代替:

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

您应该拥有:

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

这篇关于MaterialUI + React Testing库:单元测试Select MenuItem在升级到版本4后中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:38