如何使用 Jest 和 Enzyme 测试样式组件以获得 属性

How to test a styled-component to have a property with Jest and 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 中的输入是否已选中 属性 的信息。例如:

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() 找不到任何节点。

  1. 您需要设置显示名称才能使用查找:

    InputCheckbox.displayName = 'InputCheckbox';

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

    为了更方便使用babel plugin


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

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


  3. 也许在您的情况下访问子组件需要使用 'mount' 代替 'shallow'.