Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 862
Stophface Avatar asked Feb 16 '19 08:02

Stophface


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

like image 170
Andreas Köberle Avatar answered Oct 20 '22 14:10

Andreas Köberle