React Testing Library: Checkboxes and events
Published ....
Last modified ....
Share this post on BlueskySee discussion on Bluesky
TL;DR
If you're testing a checkbox input element with React Testing Library, you'll
want to fire a click event on the checkbox not a change event!
Read on to find out how I discovered this!
I was recently refactoring about 70 individual Enzyme-based unit tests across our design system codebase at work to swap it for React Testing Library, and encountered an odd quirk that I figured I'd document on my blog.
I was converting some tests for one of our Checkbox Table components, a component that allows users to select individual rows or the entire page of results shown within a table. The previous tests were quite extensive, the entire file was well over 1200 lines of code covering many different and difficult edge cases.
As I went through I converted one of the tests that was asserting on an
onChange handler being properly called when one of the checkboxes was
selected, the previous test code looked something like:
const handleChange = jest.fn();