Rstest utilities for Styled Components
npm install rstest-styled-components

toHaveStyleRule matcher to make expectations on CSS style rules.``sh`
pnpm add -D rstest-styled-components
Or with npm:
`sh`
npm install --save-dev rstest-styled-components
`js
import React from 'react'
import styled from 'styled-components'
import renderer from 'react-test-renderer'
import 'rstest-styled-components'
const Button = styled.button
color: red;
test('it works', () => {
const tree = renderer.create().toJSON()
expect(tree).toHaveStyleRule('color', 'red')
})
`
If you don't want to import the library in every test file, it's recommended to use the global installation method.
Table of Contents
=================
* Setup Options
* Plugin Setup (Recommended)
* Setup Files
* Direct Import
* Snapshot Testing
* Basic Usage
* React Testing Library
* Enzyme Support
* Serializer Options
* toHaveStyleRule
* Contributing
There are multiple ways to configure rstest-styled-components depending on your preference and rstest version:
🚀 When rstest supports plugins (future feature), configure in rstest.config.js:
`js
import { styledComponentsPlugin } from 'rstest-styled-components/plugin';
export default {
plugins: [
styledComponentsPlugin({
addStyles: true,
classNameFormatter: (index) => c${index},`
autoSetup: true
})
]
};
Benefits:
- ✅ Zero imports needed in test files
- ✅ Centralized configuration
- ✅ Automatic setup across all tests
📁 Current approach - Configure in rstest.config.js:
`js`
export default {
setupFilesAfterEnv: [
'rstest-styled-components/setup'
]
};
Benefits:
- ✅ Works today with current rstest
- ✅ No imports needed in test files
- ✅ Standard testing framework pattern
📦 Manual approach - Import in each test file:
`js`
import 'rstest-styled-components';
Benefits:
- ✅ Full control over when utilities are loaded
- ✅ Works with any testing framework
- ✅ Explicit dependencies
Rstest snapshot testing is an excellent way to test React components and ensure styles don't change unexpectedly. This package enhances the snapshot testing experience by including actual CSS rules in your snapshots and replacing dynamic class names with stable placeholders.
When you import rstest-styled-components, it automatically adds a snapshot serializer that:
1. Includes CSS rules in your snapshots
2. Replaces dynamic class names with stable placeholders (e.g., c0, c1)
3. Cleans up unreferenced class names
`js
import React from 'react'
import styled from 'styled-components'
import renderer from 'react-test-renderer'
import 'rstest-styled-components'
const Button = styled.button
color: red;
background: blue;
test('Button snapshot', () => {
const tree = renderer.create().toJSON()
expect(tree).toMatchSnapshot()
})
`
This produces a snapshot like:
`
.c0 {
color: red;
background: blue;
}
className="c0"
>
Click me
`
Works seamlessly with React Testing Library:
`js
import { render } from '@testing-library/react'
test('Button with testing library', () => {
const { container } = render()
expect(container.firstChild).toMatchSnapshot()
})
`
Also works with Enzyme shallow and mount:
`js
import { shallow, mount } from 'enzyme'
test('Button with Enzyme', () => {
const wrapper = shallow()
expect(wrapper).toMatchSnapshot()
const mounted = mount()
expect(mounted).toMatchSnapshot()
})
`
You can customize the serializer behavior:
`js
import { setStyleSheetSerializerOptions } from 'rstest-styled-components/serializer'
// Disable CSS styles in snapshots
setStyleSheetSerializerOptions({
addStyles: false
})
// Use custom class name formatting
setStyleSheetSerializerOptions({
classNameFormatter: (index) => styled-${index}`
})
Available options:
- addStyles (boolean, default: true) - Include CSS styles in snapshotsclassNameFormatter
- (function, default: (index) => \c${index}\) - Format replacement class names
You can import just the serializer without other functionality:
`js
import { styleSheetSerializer } from 'rstest-styled-components/serializer'
// Manually add the serializer
expect.addSnapshotSerializer(styleSheetSerializer)
`
The toHaveStyleRule matcher is useful to test if a given CSS rule is applied to a component.undefined
The first argument is the expected property, the second is the expected value which can be a String, RegExp, rstest asymmetric matcher or .
When used with a negated ".not" modifier the second argument is optional and can be omitted.
`js
const Button = styled.button
color: red;
border: 0.05em solid ${props => props.transparent ? 'transparent' : 'black'};
cursor: ${props => !props.disabled && 'pointer'};
opacity: ${props => props.disabled && '.65'};
test('it applies default styles', () => {
const tree = renderer.create().toJSON()
expect(tree).toHaveStyleRule('color', 'red')
expect(tree).toHaveStyleRule('border', '0.05em solid black')
expect(tree).toHaveStyleRule('cursor', 'pointer')
expect(tree).not.toHaveStyleRule('opacity') // equivalent of the following two
expect(tree).not.toHaveStyleRule('opacity', expect.any(String))
expect(tree).toHaveStyleRule('opacity', undefined)
})
test('it applies styles according to passed props', () => {
const tree = renderer.create().toJSON()
expect(tree).toHaveStyleRule('border', expect.stringContaining('transparent'))
expect(tree).toHaveStyleRule('cursor', undefined)
expect(tree).toHaveStyleRule('opacity', '.65')
})
`
The matcher supports an optional third options parameter which makes it possible to search for rules nested within an At-rule (see media and supports) or to add modifiers to the class selector.
`js
const Button = styled.button
@media (max-width: 640px) {
&:hover {
color: red;
}
}
test('it works', () => {
const tree = renderer.create().toJSON()
expect(tree).toHaveStyleRule('color', 'red', {
media: '(max-width:640px)',
modifier: ':hover',
})
})
`
If a rule is nested within another styled-component, the modifier option can be used with the css helper to target the nested rule.
`js
const Button = styled.button
color: red;
const ButtonList = styled.div
display: flex;
${Button} {
flex: 1 0 auto;
}
import { css } from 'styled-components';
test('nested buttons are flexed', () => {
const tree = renderer.create(
expect(tree).toHaveStyleRule('flex', '1 0 auto', {
modifier: css${Button},`
})
})
You can take a similar approach when you have classNames that override styles
`js
const Button = styled.button
background-color: red;
&.override {
background-color: blue;
}
const wrapper = mount();
expect(wrapper).toHaveStyleRule('background-color', 'blue', {
modifier: '&.override',
});
`
This matcher works with trees serialized with react-test-renderer, react-testing-library, or those shallow rendered or mounted with Enzyme.
It checks the style rules applied to the root component it receives, therefore to make assertions on components further in the tree they must be provided separately (Enzyme's find might help).
> Note: for react-testing-library, you'll need to pass the first child to check the top-level component's style. To check the styles of deeper components, you can use one of the getBy* methods to find the element (e.g. expect(getByTestId('styled-button')).toHaveStyleRule('color', 'blue'))
When using the plugin approach, you can customize behavior:
`js
import { styledComponentsPlugin } from 'rstest-styled-components/plugin';
export default {
plugins: [
styledComponentsPlugin({
// Include CSS styles in snapshots (default: true)
addStyles: true,
// Custom class name formatter (default: index => c${index})styled-${index}
classNameFormatter: (index) => ,`
// Auto-setup matchers and serializers (default: true)
autoSetup: true
})
]
};
Available Options:
- addStyles - Include CSS rules in snapshots
- classNameFormatter - Function to format stable class names
- autoSetup` - Automatically register matchers and serializers
Please open an issue and discuss with us before submitting a PR.