Abhi
Abhi

Reputation: 1574

fireEvent.change does not toggle checkbox

This is the component I have

 <div
  id={id}
  data-testid="checkboxWrapper"
  className={`${checkboxWrapper} ${customClass ? customClass : ''}`}
  style={style}
>
  <input
    data-testid="checkbox"
    type="checkbox"
    onChange={handleChange}
    checked={checked}
    id={`checkbox${id}`}
    name={name}
  />
  {label && <label htmlFor={`checkbox${id}`}>{label}</label>}
</div>

The change handler:

    const handleChange = () => {
      setChecked((prevValue) => !prevValue)
  }
useEffect(() => {
    onChange(value, checked)
  }, [checked, value, onChange])

The test:

it('passed value and check state to onChange props', () => {
  const onChange = (value, checked) => {}
  const { getByTestId } = render(
    <Checkbox defaultChecked onChange={onChange} />
  )
  const checkbox = getByTestId('checkbox')
  const isChecked = checkbox.checked
  fireEvent.change(checkbox)
  expect(checkbox.checked).toEqual(!isChecked) // is not correct value
})

I have the checked state in isChecked and calling fireEvent.change but the expect(checkbox.checked).toEqual(!isChecked) test fails.

What am I doing wrong?

Upvotes: 2

Views: 7668

Answers (2)

betterbuddhistbeast
betterbuddhistbeast

Reputation: 41

Try the following with a click event:

it('passed value and check state to onChange props', () => {
  const onChange = (value, checked) => {}
  const { getByTestId } = render(
    <Checkbox defaultChecked onChange={onChange} />
  )
  const checkbox = getByTestId('checkbox')
  const isChecked = checkbox.checked
  fireEvent.click(checkbox, {
                   target: {checked: false}
                 })
  expect(checkbox.checked).toEqual(!isChecked)
})

I noticed that you are using jest but not taking full advantage of it! You could modify your code a bit to be the following:

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

it('passed value and check state to onChange props', () => {
  const onChange = (value, checked) => {}
  render(
    <Checkbox defaultChecked onChange={onChange} />
  )
  const checkbox = screen.getByRole('combobox')
  fireEvent.click(checkbox, {
                   target: {checked: false}
                 })
  expect(checkbox).not.toBeChecked()
})

There's a fantastic article by Kent C. Dodds that discusses a few awesome testing techniques!

Upvotes: 4

Related Questions