are there anyone see the problem here? If I put checked in state on change it works. But I don't want to duplicate the checked state data and watch it every single props change.
Parent components gets the latest checked information and put it in own state and if parent isChecked change, FormCheckBox isChecked changes. I think, it works async and when I reach latest line of my test code, parent update does not finish, so I see the stale isChecked.
export default function FormCheckBox(props: IFormCheckBoxProps) {
const { onChange, label, isChecked, error, errorModelLabel = '' } = props
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
onChange(event.currentTarget.checked)
}
const errorMsg = getFormErrorMsg(error, errorModelLabel)
return (
<FormGroup
as={Row}
className={cx('mb-3', { 'is-invalid': errorMsg })}
controlId="catalogDescription"
data-testid="slvy-formcheckbox"
>
<FormLabel column className="d-flex align-items-center justify-content-end fw-bold" sm={2}>
{label}
</FormLabel>
<Col className="d-flex align-items-center" sm={10}>
<input
checked={isChecked}
className={cx('checkbox', { 'is-invalid': errorMsg })}
type="checkbox"
onChange={handleChange}
/>
<Form.Control.Feedback type="invalid">{errorMsg}</Form.Control.Feedback>
</Col>
</FormGroup>
)
}
it('checkbox must use fireEvent.click', async () => {
const handleChange = jest.fn()
props.isChecked = false
props.onChange = handleChange
const { container } = render(<FormCheckBox {...props} />)
const checkbox = container.querySelectorAll("input[type='checkbox']")[0] as HTMLInputElement
fireEvent.click(checkbox)
expect(handleChange).toHaveBeenCalledTimes(1)
expect(checkbox.checked).toBe(true)
})