How do you check a checkbox in react-testing-library?
To check or uncheck the checkbox using react-testing-library
, you simply want to fireEvent.click
the checkbox. There was a discussion about this on react-testing-library Issue #175. In particular, kentcdodds said:
this should probably be documented better, but with checkboxes you don't actually fire change events, you should fire click events instead.
But, based on the code you wrote above, what is the node with label text 'Locale'? Because if it has style display: none
, how would your user click to check it? Is that a typo? You should be asserting style on your dropdown but clicking on your checkbox. Maybe I'm seeing it wrong, but it looks from your code like you're doing all your assertions and operations on the same node. That doesn't seem right.
I've written up a CodeSandbox sample which has a basic div
with a style that is set to display: none
or display:block
based on whether a checkbox is checked or not. It uses react-hooks
to maintain the state.
There is also a react-testing-library
test that demonstrates asserting on the style, checking the checkbox, and then asserting the changed style.
The test code looks like this:
it('changes style of div as checkbox is checked/unchecked', () => {
const { getByTestId } = render(<MyCheckbox />)
const checkbox = getByTestId(CHECKBOX_ID)
const div = getByTestId(DIV_ID)
expect(checkbox.checked).toEqual(false)
expect(div.style['display']).toEqual('none')
fireEvent.click(checkbox)
expect(checkbox.checked).toEqual(true)
expect(div.style['display']).toEqual('block')
fireEvent.click(checkbox)
expect(checkbox.checked).toEqual(false)
expect(div.style['display']).toEqual('none')
})
Hope this helps to point you in the right direction.
I'm using "react-test-renderer": "^17.0.2"
. I've manage to do the same with a simple:
getByTestId("data-testid").click()
this is the code to get the getByTestId
:
const {getByTestId} = render(<Checkbox
onClose={jest.fn()}
onSave={onSave}
/>)