首页 > 解决方案 > 如何使用 Jest 和 Enzyme 测试样式组件以具有属性

问题描述

我有一个样式组件,它用一些样式包装了一个输入复选框元素。在我的应用程序中,默认情况下可能已经选中了此复选框。这是一些组件代码:

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

我正在使用 Jest 和 Enzyme 进行测试,但我找不到任何有关如何深入 Enzyme 浅层包装器以检查 InputCheckbox 中的输入是否将已选中属性设为 true 的信息。例如:

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

此测试失败,因为.find()找不到任何节点。

标签: javascriptreactjsjestjsenzymestyled-components

解决方案


  1. 您需要设置显示名称以供其查找:

    InputCheckbox.displayName = 'InputCheckbox';

    之后尝试 component.find('InputCheckbox')

    为了更方便使用babel 插件


  2. 还可以尝试将 find 与组件构造函数一起使用。

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


  3. 也许在你的情况下访问子组件需要使用'mount' insted of 'shallow'。

推荐阅读