【问题标题】:How to test a styled-component to have a property with Jest and Enzyme如何使用 Jest 和 Enzyme 测试样式组件以具有属性
【发布时间】:2019-09-24 20:44:56
【问题描述】:

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

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 中的输入是否已将 checked 属性设置为 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() 找不到任何节点。

【问题讨论】:

    标签: javascript reactjs jestjs enzyme styled-components


    【解决方案1】:
    1. 您需要设置显示名称以供它查找:

      InputCheckbox.displayName = 'InputCheckbox';

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

      为了更方便,请使用babel plugin


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

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


    3. 也许在你的情况下访问子组件需要使用'mount' 插入“浅”。

    【讨论】:

    • 谢谢你,这完全符合我的预期。为了避免使用mount,我只是在检查样式组件是否具有道具。
    猜你喜欢
    • 2019-05-30
    • 2017-04-09
    • 2017-04-13
    • 2020-05-10
    • 1970-01-01
    • 2019-05-01
    • 2018-10-21
    • 2019-08-23
    • 2017-02-12
    相关资源
    最近更新 更多