Unable to fire a "click" event - please provide a DOM element - Radio button JestJs

Viewed 12170

I'm writing tests to click on the value "green" radio button using Jest and React. I am facing an error

Radio Button: <input id="multicolored" name="colours" type="radio" value="green"> id="radioButton" aria-label="Radio Button" name="radio-button-field">

Radio Test:

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import ReactDOM from 'react-dom';
import Colors from './colors';
import { BrowserRouter } from 'react-router-dom';

test('It should click on radio button', async () => {
  const div = document.createElement('div');
  const dom = render(
    <BrowserRouter>
      <Colors />
    </BrowserRouter>,
    div
  );

  var input = dom.getByLabelText('Radio Button');
  fireEvent.click(input, { target: { value: 'green' } });
});

But I am facing an error. "Unable to fire a "click" event - please provide a DOM element."

Am I missing something or is there another way I can click on radio button using fireEvent?

1 Answers

On radio types you should use change instead of click in fireEvent.

fireEvent.change(input, { target: { value: 'green' } });

Hint: It is recommend to use screen to find the elements:

import { render, fireEvent, screen } from '@testing-library/react';

const radio = screen.getByLabelText('Radio Button');

DOM Testing Library also exports a screen object which has every query that is pre-bound to document.body (using the within functionality). Wrappers such as React Testing Library re-export screen so you can use it the same way. You can check on testing-library documentation.

Related