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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ramitos/jest-styled-components

v5.0.0

Published

Jest utilities for Styled Components

Downloads

2

Readme

NPM version Join the community on Spectrum

Build Status tested with jest styled with prettier

Jest Styled Components

A set of utilities for testing Styled Components with Jest. This package improves the snapshot testing experience and provides a brand new matcher to make expectations on the style rules.

Quick Start

Installation

yarn add --dev jest-styled-components

Usage

import React from 'react'
import styled from 'styled-components'
import renderer from 'react-test-renderer'
import 'jest-styled-components'

const Button = styled.button`
  color: red;
`

test('it works', () => {
  const tree = renderer.create(<Button />).toJSON()
  expect(tree).toMatchSnapshot()
  expect(tree).toHaveStyleRule('color', 'red')
})

Table of Contents

Snapshot Testing

Jest snapshot testing is an excellent way to test React components (or any serializable value) and make sure things don't change unexpectedly. It works with Styled Components but there are a few problems that this package addresses and solves.

For example, suppose we create this styled Button:

import styled from 'styled-components'

const Button = styled.button`
  color: red;
`

Which we cover with the following test:

import React from 'react'
import renderer from 'react-test-renderer'

test('it works', () => {
  const tree = renderer.create(<Button />).toJSON()
  expect(tree).toMatchSnapshot()
})

When we run our test command, Jest generates a snapshot containing a few class names (which we didn't set) and no information about the style rules:

exports[`it works 1`] = `
<button
  className="sc-bdVaJa rOCEJ"
/>
`;

Consequently, changing the color to green:

const Button = styled.button`
  color: green;
`

Results in the following diff, where Jest can only tell us that the class names are changed. Although we can assume that if the class names are changed the style rules are also changed, this is not optimal (and is not always true).

- Snapshot
+ Received

 <button
-  className="sc-bdVaJa rOCEJ"
+  className="sc-bdVaJa hUzqNt"
 />

Here's where Jest Styled Components comes to rescue.

We just import the package into our test file:

import 'jest-styled-components'

When we rerun the test, the output is different: the style rules are included in the snapshot, and the hashed class names are substituted with placeholders that make the diffs less noisy:

- Snapshot
+ Received

+.c0 {
+  color: green;
+}
+
 <button
-  className="sc-bdVaJa rOCEJ"
+  className="c0"
 />

This is the resulting snapshot:

exports[`it works 1`] = `
.c0 {
  color: green;
}

<button
  className="c0"
/>
`;

Now, suppose we change the color again to blue:

const Button = styled.button`
  color: blue;
`

Thanks to Jest Styled Components, Jest is now able to provide the exact information and make our testing experience even more delightful 💖:

- Snapshot
+ Received

 .c0 {
-  color: green;
+  color: blue;
 }

 <button
   className="c0"
 />

Enzyme

enzyme-to-json is necessary to generate snapshots using Enzyme's shallow or full DOM rendering.

yarn add --dev enzyme-to-json

It can be enabled globally in the package.json:

"jest": {
  "snapshotSerializers": [
    "enzyme-to-json/serializer"
  ]
}

Or imported in each test:

import toJson from 'enzyme-to-json'

// ...

expect(toJson(wrapper)).toMatchSnapshot()

Jest Styled Components works with shallow rendering:

import { shallow } from 'enzyme'

test('it works', () => {
  const wrapper = shallow(<Button />)
  expect(wrapper).toMatchSnapshot()
})

And full DOM rendering as well:

import { mount } from 'enzyme'

test('it works', () => {
  const wrapper = mount(<Button />)
  expect(wrapper).toMatchSnapshot()
})

Theming

In some scenario, testing components that depend on a theme can be tricky, especially when using Enzyme's shallow rendering.

For example:

const Button = styled.button`
  color: ${props => props.theme.main};
`

const theme = {
  main: 'mediumseagreen',
}

The recommended solution is to pass the theme as a prop:

const wrapper = shallow(<Button theme={theme} />)

The following function might also help:

const shallowWithTheme = (tree, theme) => {
  const context = shallow(<ThemeProvider theme={theme} />)
    .instance()
    .getChildContext()
  return shallow(tree, { context })
}

const wrapper = shallowWithTheme(<Button />, theme)

Preact

To generate snapshots of Preact components, add the following configuration:

"jest": {
  "moduleNameMapper": {
    "^react$": "preact-compat"
  }
}

And render the components with preact-render-to-json:

import React from 'react'
import styled from 'styled-components'
import render from 'preact-render-to-json'
import 'jest-styled-components'

const Button = styled.button`
  color: red;
`

test('it works', () => {
  const tree = render(<Button />)
  expect(tree).toMatchSnapshot()
})

The snapshots will contain class instead of className. Learn more.

toHaveStyleRule

The toHaveStyleRule matcher is useful to test if a given rule is applied to a component. The first argument is the expected property, the second is the expected value (string or RegExp).

test('it works', () => {
  const tree = renderer.create(<Button />).toJSON()
  expect(tree).toHaveStyleRule('color', 'red')
})

The matcher supports a third options parameter which makes it possible to search for rules nested within an At-rule (media and supports) or to add modifiers to the class selector. This feature is supported in React only, and more options are coming soon.

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',
  })
})

This matcher works with trees serialized with react-test-renderer and shallow renderered 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).

To use the toHaveStyleRule matcher with React Native, change the import statement to:

import 'jest-styled-components/native'

Global installation

It is possibile to setup this package for all the tests using the setupTestFrameworkScriptFile option:

"jest": {
  "setupTestFrameworkScriptFile": "./setupTest.js"
}

And import the library once in the setupTest.js as follows:

import 'jest-styled-components'

styled-components < v2

To use this package with styled-components < v2 (e.g. v1.4.6) the following annotation must be added at the top of the test files. Consequently, it won't be possible to use Enzyme's full DOM rendering.

/**
 * @jest-environment node
 */

Contributing

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