Testing radio inputs with React Testing Library - no form control was found associated to that label
Asked Answered
P

1

6

I am testing several radio inputs in my form using React Testing Library. Most of them have labels of yes/no so I cannot use findByLabelText. The full error I am getting is: Found a label with the text of: yes, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly. .

Here is one of my failing tests:

    test('Sealing Properly radio input should exist, be unchecked, and be clickable', async () => {
        render(
            <Component />
        );
        const sealingProperlyRadioGroup = await screen.findByTestId('sealingProperly');
        const sealingProperlyRadio = await within(sealingProperlyRadioGroup).findByLabelText('yes');
        expect(sealingProperlyRadio).toBeInTheDocument();
        expect(sealingProperlyRadio).not.toBeChecked();
        fireEvent.click(sealingProperlyRadio)
        expect(sealingProperlyRadio).toBeChecked();
    });

And this is the html that gets outputted after the error:

 <div
      class="radioGroup mb-3"
      data-testid="sealingProperly"
    >
      <label
        class="radio"
        for="sealingProperlyYes"
      >
        <input
          id="sealingProperlyYes"
          name="sealingProperly"
          required=""
          type="radio"
          value="yes"
        />
        Yes
      </label>
      <label
        class="radio ms-5"
        for="sealingProperlyNo"
      >
        <input
          id="sealingProperlyNo"
          name="sealingProperly"
          required=""
          type="radio"
          value="no"
        />
        No
      </label>
    </div>
Peal answered 3/1, 2023 at 20:30 Comment(2)
Did you try "Yes"?Feign
Wow I'm an idiot! Good catch! I switched it to /yes/i and passing no problems now! Thank you so much!Peal
P
3

I think there are a couple of problems:

  1. The text you are querying is "yes" while in your component it is capitalized. There are ways to ignore case sensitivity in React Testing Library but by default it is case sensitive. You can learn more about it here
  2. In React the for attribute is written slightly differently - htmlFor="your-id" so I think your labels don't get associated with their inputs correctly. source
Preshrunk answered 4/1, 2023 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.