Check if checkbox is checked with jest/enzyme

How do I test if several checkboxes are checked or not?

render() ... <React.Fragment> <div className='foo'> <label> <input className='checkbox' name='bar' type='checkbox' checked={this.props.checked} onChange={() => { } } /> </label> </div> </React.Fragment> ...

I tried

it('checks all checkboxes', () => { const component = shallow( <Foo ... /> ) expect(component .find('input[type="checkbox"][checked="checked"]')) .toHaveLength(content.length);
});

and

component .find({ type: 'checkbox' }) .forEach(node => { expect(node .props .checked) .toEqual(true); });

or

component .find('input') .forEach(node => { expect(node .props .checked) .toEqual(true); });

and

component .find('.checkbox') .forEach(node => { expect(node .props .checked) .toEqual(true); });

The last three give me undefined while the first one returns a massive object ({Symbol(enzyme.__root__): {Symbol(enzyme.__root__): [Circular], Symbol(enzyme.__unrendered__): <Foo....

2 Answers

You just miss that props is a function that returns the props (and not accesses the props directly), so you have to call it:

component .find('input') .forEach(node => { expect(node .props() .checked) .toEqual(true); });
0

With jest-dom, you can use expect(node).toBeChecked();

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like