【问题标题】:Test styled-components with Enzyme用 Enzyme 测试 styled-components
【发布时间】:2017-11-01 02:18:35
【问题描述】:

我有一个关于酶测试的问题,所以基本上我正在做的事情是这样的:

const BaseButton = styled.button`
  padding: 10px;
`;

const PrimaryButton = BaseButton.extend`
  color: red;
`;

const SecondaryButton = BaseButton.extend`
  color: blue;
`;

// My actual component:
const buttonTypes = {
    primary: PrimaryButton,
    secondary: SecondaryButton
};
export const Button = (props: Props) => {
    const { type = 'primary' } = props;
    const Btn = buttonTypes[type] || buttonTypes.primary;

    return (
        <Btn
            {...props}
            onClick={props.onClick}
        >
            {props.children}
        </Btn>
    );
};

我想用 Enzyme 在 type 上传递不同的 props 做一些测试,例如测试应该是这样的:

should render a Primary button if type='primary'

should render a Secondary button if type='secondary'

should render a Primary button if type=''

should render a Primary button by default

我的按钮有更多的属性,但为了简单起见,我只显示了color。

关于如何实现这一目标的任何想法?

【问题讨论】:

    标签: reactjs enzyme styled-components


    【解决方案1】:

    我最终做的是:

    1. 为按钮添加数据属性
    2. 使用 Enzyme 安装组件
    3. 安装后,我使用component.html() 将组件作为字符串获取
    4. 检查是否应用了正确的属性
    // Button.js
    const buttons = {
        primary: 'primary',
        secondary: 'secondary'
    };
    
    export const ButtonStyles = styled.button.attrs({
        'data-button-type': props => buttons[props.type] || buttons.primary
    })`
        padding: 10px;
    `;
    
    // Button.tests.js
    
    it('should render a primary button when type prop is missing', () => {
        const wrapper = mount(
            <Button
                {...defaultProps}
                type=""
            />
        );
    
        expect(wrapper.html().includes('data-button-type="primary"')).toBeTruthy();
    });
    

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 2020-12-17
      • 2019-05-02
      • 2018-07-18
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 2021-04-06
      • 2017-08-02
      相关资源
      最近更新 更多