Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 353
Viny Machado Avatar asked Jan 02 '20 17:01

Viny Machado


1 Answers

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"));
like image 139
Ryan Cogswell Avatar answered Nov 10 '22 01:11

Ryan Cogswell