Check if checkbox is checked with jest/enzyme
Mia Lopez
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();