How do I trigger a change event on radio buttons in react-testing-library?
First, you don’t have to call rerender
. You use rerender
only when you want the component to receive different props. See link.
Whenever you call fireEvent the component will render like it would in your normal app. It’s correct to fire a change event, but you must pass a second parameter with the event data.
This example works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import React from "react"; import { render, fireEvent } from "react-testing-library"; test("radio", () => { const { getByLabelText } = render( <form> <label> First <input type="radio" name="radio1" value="first" /> </label> <label> Second <input type="radio" name="radio1" value="second" /> </label> </form> ); const radio = getByLabelText('First') fireEvent.change(radio, { target: { value: "second" } }); expect(radio.value).toBe('second') }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.