Testing Styled Components

Published on 9/27/2020

If you are working with Styled Components and also use test tracking software like Codecov to track test coverage on your pull requests, you may have encountered an issue with Styled Components lowering your test coverage score.

Say you have a component that looks like this:

1  export const StyledText = styled.p`
2    ${({ theme }) => css`
3      font-size: 134x;
4      color: ${theme.colors.gray};
5    `}
6  `;

Tools like Codecov will count this as an untested function, even if you use something like a snapshot to test the component where this is being used, or if you test the parent component.

So how do you test this?

It wasn't immediately apparent to me, and I didn't find much in documentation about it, so I wanted to share how I solved it. It was actually quite easy.

import renderer from 'react-test-renderer';
// if you're using a theme, you would import it here
// or you could create a mock theme
import theme from 'theme'

describe('StyledText', () => {

  it('StyledText component has correct props', () => {
    const styledText = renderer.create(
    <StyledText theme={theme}></StyledHeadline>).toJSON();
    expect(styledText).toHaveStyleRule('color', theme.colors.gray);


Let's break this down. We use renderer from react-test-renderer to create the component and turn that to JSON. We then parse that and assert that the component has the style rules we expect with toHaveStyleRule.

You can test multiple props in this same way as well.

Once you do this, your test coverage should now mark your Styled Component as tested.