How can I test a MUI check box with no label using data-testid?
Asked Answered
S

1

5

I want to test a checkbox that has no label. The point is that there are other checkboxes as well so I cant use getByRole.

I have tried to use data-testid, but apparently, it's not working.

How am I supposed to check if that checkbox is checked(toBeChecked())?

<Checkbox
  data-testid={item?.id}
  key={item?.id}
  id={item?.id.toString()}
  color="secondary"
  checked={item?.checked}
  disabled={hasAll}
  onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
    if (item) {
      item.checked = e.target.checked;
      setFinalData(updateItemInArray(finalData, {
        item,
        index,
      }));
    }
  }}
/>
Structure answered 5/4, 2022 at 12:20 Comment(3)
Why does the checkbox not have a label? How will users needing assistive technology like a screenreader know what this checkbox means?Antiperistalsis
Because I am using it inside a table, other related data are in other cells of the row.Structure
But then you still have to connect the other data through aria-label or aria-labelled by so it is accessible for everybodyAntiperistalsis
A
8

The proper way to do this would be to add an aria-label to your checkbox, so it's announced correctly by screen readers:

<Checkbox inputProps={{ 'aria-label': 'Select row 1' }} />

This way, you'll be able to select it in your tests using getByLabelText.

If you want to use data-testid, you can place it on the checkbox similarly to aria-label:

<Checkbox inputProps={{ 'data-testid': 'checkbox1' }} />

Note that if you're using Typescript, you'd have to cast the inputProps to React.InputHTMLAttributes<HTMLInputElement> as data attributes are not a part of InputHTMLAttributes:

<Checkbox inputProps={{ 'data-testid': 'checkbox1' } as React.InputHTMLAttributes<HTMLInputElement>} />
Atelier answered 6/4, 2022 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.