Search⌘ K
AI Features

Making Style Assertions for Styled Components Testing

Explore making style assertions for styled-components in React using the jest-styled-components plugin. Understand how to test dynamic and static styles, extend styled components, and improve test coverage. Gain practical knowledge of verifying style rules and using Jest to ensure styling behaves as expected in your React applications.

We'll cover the following...

Making assertions about styles

The following is how to make different assertions about styles:

  • To make assertions about the styles that styled-components generate, you’ll need the Jest styled-components plugin. Install jest-styled-components with npm:

    $ npm install --save-dev jest-styled-components@6.3.1
    + jest-styled-components@6.3.1
    
  • Then you’ll need to bring in the plugin before running your tests:

Javascript (babel-node)
import Adapter from 'enzyme-adapter-react-16';
import { configure } from 'enzyme';
import 'jest-styled-components';
configure({ adapter: new Adapter() });
  • Now you have a new assertion at your disposal, toHaveStyleRule(). Add a test to the describe('Img') block to make sure that the expected styled.img styles are coming through:
...