Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-testing-library for material ui Text input

My Text Input is:

<TextField
  className={classes.textField}
  data-testid={name}
  variant="outlined"
  error={false}
  required
  onChange={(element) => {
    if (onTextChange) {
      onTextChange(name, element.target.value);
    }
  }}
  disabled={!editEnable}
  name={name}
  label={label}
  defaultValue={values}
  fullWidth
/>;

and UI:

Screenshot of HTML with an input field highlighted

How to change the value of this text element in the React testing library?

like image 689
Ruchin Kumar Avatar asked Sep 01 '20 20:09

Ruchin Kumar


2 Answers

In my case it works like this

it('should render input ', () => {
    const field  = screen.getByTestId('search-text-field').querySelector('input')
    expect(field ).toBeInTheDocument()

    fireEvent.change(field , {target: { value: 'google it'}});
    expect(field.value).toBe('google it');
});
like image 82
Ivan K. Avatar answered Nov 08 '22 21:11

Ivan K.


I don't think getting the input by the display value is a good idea as if that changes the whole test will fail. Instead you should get the label of the input field.

screen.getByLabelText(/^label/i)

Update

Just realised that my way only works if you include an id to the TextField and the ID must match the name. This does seem to be the preferred way to get the input via Material UI as you don't need to include a test-id or by the value.

<TextField
    name={name}
    id={name}
    label={label}
    {...otherProps}
/>
like image 43
Richard Hpa Avatar answered Nov 08 '22 20:11

Richard Hpa