Juan Rivas
Juan Rivas

Reputation: 603

How to test a styled-component to have a property with Jest and Enzyme

I have a styled-component wrapping an input checkbox element with some styling. In my app, this checkbox could be already checked by default. This is some of the component code:

const InputCheckbox = styled.input.attrs((props) => ({
    id: props.id,
    type: 'checkbox',
    checked: props.checked
}))`
    visibility: hidden;

    &:checked + label {
        background-color: ${(props) => props.theme.mainColor};
        border-color: ${(props) => props.theme.mainColor};

        &:after {
            border-left: 2px solid #fff;
            border-bottom: 2px solid #fff;
        }
    }
`;


function Checkbox(props) {
    return (
        <CheckboxContainer>
            <InputCheckbox
                id={props.id}
                checked={props.checked}
                onChange={(event) => {
                    props.onChange(event.target.checked);
                }}
            />
            <CheckboxLabel id={props.id} />
        </CheckboxContainer>
    );
}

I'm using Jest and Enzyme for testing but I couldn't find any information on how dive into your Enzyme shallow wrapper to check that the input inside my InputCheckbox has the checked property as true. For example:

describe('Checkbox', () => {
    const mockProps = {
        id: 'settings-user',
        checked: true,
        onComplete: (id) => jest.fn(id)
    };

    const component = shallow(<Checkbox {...mockProps}/>);

    describe('on initialization', () => {
        it('Input should be checked', () => {
            const inputCheckbox = component.find('InputCheckbox');
            expect(inputCheckbox.props().checked).toBe(true);
        });
    });
});

This test fails because the .find() can't find any node.

Upvotes: 0

Views: 1784

Answers (1)

Timofey Goncharov
Timofey Goncharov

Reputation: 1148

  1. You need set display name for use find by it:

    InputCheckbox.displayName = 'InputCheckbox';

    After that try component.find('InputCheckbox')

    For more convenience use babel plugin.


  2. Also try use find with component constructor.

    import InputCheckbox from 'path-to-component';
    
    ...
    
    const inputCheckbox = component.find(InputCheckbox);
    
    


  3. Perhaps for access child component in you case need use 'mount' insted of 'shallow'.

Upvotes: 1

Related Questions