Writing unit testcase for a checkbox with reactt testing library

Viewed 66
const CheckBox = (props) => {
    const { className, active = false, onClick = () => { }, label = '', isHidden=false } = props;
    if(isHidden) return null;
    return <StyledCheckBox className={className} onClick={() => onClick(!active)} >
        <div data-testid="CHECKBOX_ID" className={`box ${active ? 'active' : 'inactive'}`}>
            {active && <div className='check-mark' />}
        </div>
        <div className='label'>{label}</div>
    </StyledCheckBox>
}

how should i write test case for this if i have to see if the checkbox is selected or not?

1 Answers

So I would do it like so; assert it exists, assert it's initially unchecked, create click event, assert its selected by asserting check-mark div appears.

it('test case example', () => {
   const { getByTestId, getByRole, container } = render(<CheckBox {...props} />)
   const activeDiv = container.querySelector('.check-mark') // get div
   expect(activeDiv).toBeFalsy() // assert doesn't exist when un-checked
   expect(getByTestId('CHECKBOX_ID')) // assert checkbox comp exists
   expect(getByRole('checkbox')).not.toBeChecked() // assert it isn't checked
   userEvent.click(getByRole('checkbox')) // click the checkbox
   expect(getByRole('checkbox')).toBeChecked() // assert it is checked
   expect(activeDiv).toBeTruthy() // assert div shows after active
})

Does this help?

Related