What is jest-styled-components?
jest-styled-components is a Jest utility for testing styled-components. It provides custom matchers to test the styles applied to your components, making it easier to ensure that your styled-components are rendered correctly.
What are jest-styled-components's main functionalities?
toHaveStyleRule
The `toHaveStyleRule` matcher allows you to check if a specific style rule is applied to a component. In this example, it verifies that the `Button` component has a `color` style rule set to `red`.
const styled = require('styled-components').default;
const { toHaveStyleRule } = require('jest-styled-components');
expect.extend({ toHaveStyleRule });
const Button = styled.button`
color: red;
`;
// Test
it('should have red color', () => {
const wrapper = mount(<Button />);
expect(wrapper).toHaveStyleRule('color', 'red');
});
toMatchSnapshot
The `toMatchSnapshot` matcher allows you to take a snapshot of the rendered component and compare it to a previously saved snapshot. This is useful for ensuring that the component's styles have not changed unexpectedly.
const styled = require('styled-components').default;
const { toMatchSnapshot } = require('jest-styled-components');
expect.extend({ toMatchSnapshot });
const Button = styled.button`
color: red;
`;
// Test
it('should match the snapshot', () => {
const wrapper = mount(<Button />);
expect(wrapper).toMatchSnapshot();
});
Other packages similar to jest-styled-components
jest-emotion
jest-emotion is a Jest utility for testing Emotion styled components. It provides custom matchers to test the styles applied to your components, similar to jest-styled-components. However, it is specifically designed for Emotion, another popular CSS-in-JS library.
enzyme-to-json
enzyme-to-json is a utility for converting Enzyme wrappers to a format compatible with Jest snapshots. While it does not provide style-specific matchers, it can be used in conjunction with Enzyme to test the rendered output of styled-components.
react-testing-library
react-testing-library is a lightweight solution for testing React components. It focuses on testing components from the user's perspective and can be used with jest-styled-components to test styled-components. It does not provide style-specific matchers but can be used to test the overall behavior and appearance of components.
Jest Styled Components
Jest utilities for Styled Components
Preview
Installation
yarn add --dev jest-styled-components
Usage
"jest": {
"testEnvironment": "node"
}
import { matcher, serializer } from 'jest-styled-components'
expect.extend(matcher)
expect.addSnapshotSerializer(serializer)
expect(tree).toMatchStyledComponentsSnapshot()