Search code examples
reactjsunit-testingmocha.jstddenzyme

How can I test styles from props in a styled component?


Good afternoon, I am a begginer in unit testing. I created a component <CustomLink /> in it I use styled-component Link. I need to write a unit test using any of the tools (Mocha, Enzime, etc.) except Jest, which would check that the font in my styled-component is 18px.

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

Styled-component:

import styled from 'styled-components';

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

Solution

  • you can write unit tests for your styled-components with jest-styled-components library very easily.
    like this:

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

    you can read more:
    https://www.npmjs.com/package/jest-styled-components