fireEvent.change不切换复选框

时间:2020-07-21 02:28:55

标签: reactjs jestjs react-testing-library

这是我拥有的组件

 <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>

变更处理程序:

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

测试:

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
})

我在isChecked中处于检查状态,并调用fireEvent.change,但是expect(checkbox.checked).toEqual(!isChecked)测试失败。

我在做什么错了?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

通过点击事件尝试以下操作:

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)
})

我注意到您正在使用jest,但没有充分利用它!您可以对代码进行如下修改:

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()
})

肯特C.多德斯(Kent C. Dodds)精彩的article讨论了一些很棒的测试技术!