npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

rstest-styled-components

v2.0.0

Published

Rstest utilities for Styled Components

Readme

NPM version styled with prettier

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-components

Or with npm:

npm install --save-dev rstest-styled-components

Usage

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:

  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
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 snapshots
  • classNameFormatter (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 the getBy* 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 snapshots
  • classNameFormatter - Function to format stable class names
  • autoSetup - Automatically register matchers and serializers

Contributing

Please open an issue and discuss with us before submitting a PR.