Search code examples
reactjsreact-testing-library

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


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>

Solution

  • 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