rstest-styled-components
v2.0.0
Published
Rstest utilities for Styled Components
Readme
Rstest Styled Components
A set of utilities for testing Styled Components with Rstest.
This package provides a toHaveStyleRule matcher to make expectations on CSS style rules.
Quick Start
Installation
pnpm add -D rstest-styled-componentsOr with npm:
npm install --save-dev rstest-styled-componentsUsage
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(<Button />).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
There are multiple ways to configure rstest-styled-components depending on your preference and rstest version:
Plugin Setup (Recommended)
🚀 When rstest supports plugins (future feature), configure in rstest.config.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
Setup Files
📁 Current approach - Configure in rstest.config.js:
export default {
setupFilesAfterEnv: [
'rstest-styled-components/setup'
]
};Benefits:
- ✅ Works today with current rstest
- ✅ No imports needed in test files
- ✅ Standard testing framework pattern
Direct Import
📦 Manual approach - Import in each test file:
import 'rstest-styled-components';Benefits:
- ✅ Full control over when utilities are loaded
- ✅ Works with any testing framework
- ✅ Explicit dependencies
Snapshot Testing
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.
Basic Usage
When you import rstest-styled-components, it automatically adds a snapshot serializer that:
- Includes CSS rules in your snapshots
- Replaces dynamic class names with stable placeholders (e.g.,
c0,c1) - Cleans up unreferenced class names
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(<Button>Click me</Button>).toJSON()
expect(tree).toMatchSnapshot()
})This produces a snapshot like:
.c0 {
color: red;
background: blue;
}
<button
className="c0"
>
Click me
</button>React Testing Library
Works seamlessly with React Testing Library:
import { render } from '@testing-library/react'
test('Button with testing library', () => {
const { container } = render(<Button>Click me</Button>)
expect(container.firstChild).toMatchSnapshot()
})Enzyme Support
Also works with Enzyme shallow and mount:
import { shallow, mount } from 'enzyme'
test('Button with Enzyme', () => {
const wrapper = shallow(<Button>Click me</Button>)
expect(wrapper).toMatchSnapshot()
const mounted = mount(<Button>Click me</Button>)
expect(mounted).toMatchSnapshot()
})Serializer Options
You can customize the serializer behavior:
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
Import Serializer Separately
You can import just the serializer without other functionality:
import { styleSheetSerializer } from 'rstest-styled-components/serializer'
// Manually add the serializer
expect.addSnapshotSerializer(styleSheetSerializer)toHaveStyleRule
The toHaveStyleRule matcher is useful to test if a given CSS rule is applied to a component.
The first argument is the expected property, the second is the expected value which can be a String, RegExp, rstest asymmetric matcher or undefined.
When used with a negated ".not" modifier the second argument is optional and can be omitted.
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(<Button />).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(<Button disabled transparent />).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.
const Button = styled.button`
@media (max-width: 640px) {
&:hover {
color: red;
}
}
`
test('it works', () => {
const tree = renderer.create(<Button />).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.
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(<ButtonList><Button /></ButtonList>).toJSON()
expect(tree).toHaveStyleRule('flex', '1 0 auto', {
modifier: css`${Button}`,
})
})You can take a similar approach when you have classNames that override styles
const Button = styled.button`
background-color: red;
&.override {
background-color: blue;
}
`
const wrapper = mount(<Button className="override">I am a button!</Button>);
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 thegetBy*methods to find the element (e.g.expect(getByTestId('styled-button')).toHaveStyleRule('color', 'blue'))
Plugin Configuration Options
When using the plugin approach, you can customize behavior:
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}`)
classNameFormatter: (index) => `styled-${index}`,
// Auto-setup matchers and serializers (default: true)
autoSetup: true
})
]
};Available Options:
addStyles- Include CSS rules in snapshotsclassNameFormatter- Function to format stable class namesautoSetup- Automatically register matchers and serializers
Contributing
Please open an issue and discuss with us before submitting a PR.
