【问题标题】:How can I test styles from props in a styled component?如何从样式组件中的道具测试样式?
【发布时间】:2020-07-07 21:28:03
【问题描述】:

下午好,我是单元测试的初学者。我在其中创建了一个组件<CustomLink />,我使用样式组件Link。我需要使用除 Jest 之外的任何工具(Mocha、Enzime 等)编写单元测试,它会检查我的样式组件中的字体是否为 18px。

export const CustomLink = props => {
    return(
        <WrapperLink>
            <Link fontSize="18px">{props.text}</Link>
        </WrapperLink>
    )
};

样式化组件:

import styled from 'styled-components';

    export const Link = styled.a`
        font-size: ${props => props.fontSize};
        cursor: pointer;
    `;

【问题讨论】:

    标签: reactjs unit-testing mocha.js tdd enzyme


    【解决方案1】:

    您可以使用jest-styled-components 库非常轻松地为您的样式化组件编写单元测试。
    像这样:

    import React from "react";
    import styled from "styled-components";
    import renderer from "react-test-renderer";
    import "jest-styled-components";
    
    export const Link = styled.a`
      font-size: ${props => props.fontSize};
      cursor: pointer;
    `;
    
    test("it tests props", () => {
      const tree = renderer.create(<Link fontSize={18} />).toJSON();
      expect(tree).toHaveStyleRule("font-size", "18");
    });
    

    您可以阅读更多:
    https://www.npmjs.com/package/jest-styled-components

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 2020-01-24
      • 2019-03-03
      • 2017-11-02
      • 1970-01-01
      • 2020-06-11
      • 2020-01-21
      • 1970-01-01
      • 2021-08-24
      相关资源
      最近更新 更多