Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing material-ui TextField by role using react-testing-library

I have some components which include some mui TextFields, and there are two situations for my components:

  1. One TextField is designed for LicenseCode and it can't have a label.

  2. Also there are some TextFields that will be created via the map function also I can't use the label for each of them.

So, I can't use getByRole for testing them. To mitigate this in testing I've tried some solutions, But I think there should be a better way. These are my founded solutions:

  1. I've disabled eslint and use documentQuerySecletor for that.
  /*eslint-disable */
  const activationCodeInputs = document.querySelectorAll('.codeItem input');
  expect(activationCodeInputs).toHaveLength(5);

  const systemIdTextarea = document.getElementById('systemId');
  expect(systemIdTextarea).not.toBeNull();
  /*eslint-enable */
  1. Also, Find an article that used data-testid and passed it to TextField viainputProps
// code
<TextField
 inputProps={{ 'data-testid': 'activationCode' }}
/>

 <TextField
  inputProps={{ 'data-testid': 'systemId' }}
 />

// tests
const activationCodeInputs = screen.getAllByTestId('activationCode');
expect(activationCodeInputs).toHaveLength(5);

const systemIdTextarea = screen.getByTestId('systemId');
expect(systemIdTextarea).toBeInTheDocument();

Since it is just a text field which is a regular element, Do I have to write tests with getByRole only as the doc says the first preferred way, is it?

like image 253
SeyyedKhandon Avatar asked Oct 29 '25 17:10

SeyyedKhandon


1 Answers

For Material UI and React Testing I've just used a label on the Textfield and used getByLabelText for testing to get the input with that label

 <TextField
   label="input label"
   variant="outlined"
 />


screen.getByLabelText(/^input label/i)
like image 114
Richard Hpa Avatar answered Oct 31 '25 06:10

Richard Hpa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!