🔧 💅 Jest utilities for Styled Components

Overview

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

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

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 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()
})

react-testing-library

To generate snapshots with react-testing-library, you can follow the example below:

import { render } from '@testing-library/react'

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

The snapshots will contain class instead of className because the snapshots are of DOM elements

Theming

In some scenarios, 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 for shallow rendering:

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

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

and for full DOM rendering:

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

  return mount(tree, {
    context,
    childContextTypes: ThemeProvider.childContextTypes,
  })
}

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.

Serializer

The serializer can be imported separately from jest-styled-components/serializer. This makes it possible to use this package with specific-snapshot and other libraries.

import React from 'react'
import styled from 'styled-components'
import renderer from 'react-test-renderer'
import { styleSheetSerializer } from "jest-styled-components/serializer"
import { addSerializer } from "jest-specific-snapshot"

addSerializer(styleSheetSerializer)

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

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

Serializer Options

The serializer can be configured to control the snapshot output.

import { render } from '@testing-library/react'
import { setStyleSheetSerializerOptions } from 'jest-styled-components/serializer'

setStyleSheetSerializerOptions({
  addStyles: false,
  classNameFormatter: (index) => `styled${index}`
});

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

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 which can be a String, RegExp, Jest 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. 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',
  })
})

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

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

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

import 'jest-styled-components/native'

Global installation

It is possible to setup this package for all the tests. Import the library once in the src/setupTests.js as follows:

import 'jest-styled-components'

Working with multiple packages

If Jest Styled Components is not working, it is likely caused by loading multiple instances of styled-components. This can happen especially when working with a Lerna monorepo. Starting with [email protected], a warning will be logged when multiple instances of it are being included and run as part of the Jest tests. Using [email protected] and lower with multiple instances will cause a silent error with unexpected results.

To debug and fix multiple instances of styled-components see the FAQ on "Why am I getting a warning about several instances of module on the page?".

Contributing

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

Comments
  • Bring compatibility with v4

    Bring compatibility with v4

    Hi @MicheleBertoli, just a quick one to see what your plan is to add compatibility with styled-components v4.

    Right now jest-styled-components cannot really be used with v4; the main issue I came across so far is that when using Enzyme Shallow Rendering this renders an element like the following: <BaseStyledComponent theme={{...}} forwardedClass={{...}} forwardedRef={{...}} />

    The getHTML function will print this when that component is passed: <style data-styled="" data-styled-version="4.0.0-beta.5"> /* sc-component-id: sc-bdVaJa */ </style> Which means no styles rules can be found.

    Everything works normally when using Full DOM Rendering since that would render

    <ForwardRef theme={{...}}>
      <BaseStyledComponent theme={{...}} forwardedClass={{...}} forwardedRef={{...}}>
        <label className="sc-bdVaJa bGCxuB" />
      </BaseStyledComponent>
    </ForwardRef>
    

    Giving then access to the actual styled component (in the example above the label).

    help wanted styled components 
    opened by santino 42
  • Styles not found on a component (toHaveStyleRule)

    Styles not found on a component (toHaveStyleRule)

    With the latest enzyme (3.4.1) and jest-styled-components (6.0.0), the toHaveStyleRule assertion is not finding the styles on a component.

    Symptoms:

        No style rules found on passed Component
    
          28 |         .dive()
          29 |         .dive()
        > 30 |     ).toHaveStyleRule('text-align', 'center')
          31 |   })
          32 |
    

    Also visible in snapshots. Before, the snapshot included the style classes definition, e.g.:

    .c0 {
      padding-left: 0;
     ...
      display: table-cell;
    }
    

    With the latest enzyme, in the snapshot, the className is still there on a component (twice?), but the class definition is missing:

    <MyComponent
      centre={false}
      className="c0"
      className="... obnHq"
    
    no repro 
    opened by msbober 32
  • Not working with styled-components v3.0.0

    Not working with styled-components v3.0.0

    Broken as styled-components isn't shipping with /lib anymore (https://github.com/styled-components/styled-components/releases/tag/v3.0.1)

    Cannot find module 'styled-components/lib/models/StyleSheet' from 'utils.js
    
    opened by corygibbons 24
  • Match snapshot fails with

    Match snapshot fails with "undefined:3:21: property missing ':'"

    I have this test:

    import 'jest-styled-components';
    import React from 'react';
    import { truncate } from '../style';
    import styled from 'styled-components';
    import { shallow } from 'enzyme';
    
    describe('shared/utils/string/isBlank', () => {
      it('should return the css with width', () => {
        const Result = styled.div`
          color: red;
          ${truncate({ width: 100 })};
        `;
        const wrapper = shallow(<Result />);
        expect(wrapper).toMatchSnapshot();
      });
    });
    

    And this truncate function

    export function truncate({ maxWidth, width }) {
      return `
        ${({ maxWidth }) => maxWidth && `max-width: ${maxWidth}px;`}
        ${({ width }) => width && `width: ${width}px;`}
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      `;
    }
    

    However, when I try to match the snapshot I'm getting:

        undefined:3:21: property missing ':'
    
          at Object.it (src/shared/utils/__tests__/style.js:22:21)
              at Promise (<anonymous>)
          at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
              at <anonymous>
          at process._tickCallback (internal/process/next_tick.js:188:
    

    Seems like jest-styled-components doesn't like those nested functions because if I remove them it works.

    opened by topicus 21
  • Having trouble with enzyme mount of tree that depends on theme

    Having trouble with enzyme mount of tree that depends on theme

    I know this is a topic that has been marked as "tricky" but I could really use some help to understand how to best go about testing a tree that has components that depend on theme using enzyme's mount rendering.

    I have tried the following solutions to no avail:

     import React from 'react'
    import { mount, shallow } from 'enzyme'
    import { ThemeProvider } from 'styled-components'
    import createBroadcast from 'styled-components/lib/utils/create-broadcast'
    
    import theme from 'theme'
    
    const CHANNEL = '__styled-components__'
    const broadcast = createBroadcast(theme)
    
    const nodeWithThemeProp = node => {
      return React.cloneElement(node, { [CHANNEL]: broadcast.subscribe })
    }
    
    export const mountWithTheme = (node, { context, childContextTypes } = {}) => {
      return mount(nodeWithThemeProp(node), {
        context: Object.assign({}, context, { [CHANNEL]: broadcast.subscribe }),
        childContextTypes: Object.assign(
          {},
          { [CHANNEL]: createBroadcast(theme).publish },
          childContextTypes
        )
      })
    }
    

    AND:

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

    Any direction you could provide?

    opened by duro 20
  • toHaveStyleRule does not work with babel-plugin-styled-components

    toHaveStyleRule does not work with babel-plugin-styled-components

    When using the latest version alongside babel-plugin-styled-components, the toHaveStyleRule matcher always fails ("No style rules found on passed Component").

    This issue seems to have been caused by this commit: https://github.com/styled-components/jest-styled-components/commit/8c2ea4a0a8789e11707e7f18e76b811e0d70c4c0#diff-4eed74593d3d8efde6a0959c9c35119bR71

    Specifically, this line assumes classnames will have a sc- prefix which is not present:

    const staticClassNames = classNames.filter(x => x.startsWith("sc-"));
    

    (similar issue to #285)

    opened by joshjg 19
  • Add a helper to quickly provide a theme context w/o the ThemeProvider HOC

    Add a helper to quickly provide a theme context w/o the ThemeProvider HOC

    There have been a lot of workaround and a lot of confused users around how to test theming.

    https://github.com/styled-components/styled-components/issues/624

    The general problem is that wrapping a StyledComponent element in the ThemeProvider is not acceptable as it won't allow access to all enzyme methods for example.

    Thus it's desirable to write a quick helper that creates a theme context or sth similar. Maybe it should also just be solved using some documentation.

    For better or for worse, I'm going to lock the issue on the SC repo and continue a discussion for a solution here, since this can be solved using a simple helper and some text, instead of a huge, elongated issue on the styled-components repo, where people don't immediately spot the right workaround.

    cc @MicheleBertoli (sorry 😆 let's see if this goes well)

    enhancement help wanted 
    opened by kitten 19
  • Support styled-components v2

    Support styled-components v2

    Since 1.4 is listed as a peerdependency I'm assuming it's only meant to work with v1. I'm asking because I'm using v2 and would like to use this lib as well, but I've been running into some issues (window is not defined on CI tests, even with testEnvironment: node). Wondering if that's expected because it isn't officially supported, or that I'm doing something wrong.

    opened by ismay 18
  • Can't get Jest to work with Styled Components which contain theming

    Can't get Jest to work with Styled Components which contain theming

    Hi everyone,

    I've been trying all day to get Jest working with my Styled Components. I opened the following Stack Overflow question to get some help with it.

    All of the explanation (and more) about my problems you can find on that page. Does any one here has any idea on how to solve this problem?

    All help will be greatly appreciated!

    question 
    opened by daviddelusenet 15
  • Using toHaveStyleRule on nested classes

    Using toHaveStyleRule on nested classes

    I havn't been able to find any documentation on using toHaveStyleRule for checking properties on nested classes.

    Let's say I have a stylesheet for a styled component that looks like this:

    export default styled.div`
      position: relative;
      line-height: 24px;
      width: ${props => props.width};
      height: 72px;
    
      label {
        color: ${props => {
          if (!props.hasValue && !props.meta.active) {
            return props.theme.lightGrey
          }
          if (props.meta.touched && props.meta.error) {
            return props.theme.errorColor
          }
          if (props.meta.touched && props.meta.warning) {
            return props.theme.warningColor
          }
          return props.theme.brandColor
        }};
      }
    
      .placeholder {
        color: ${props => props.theme.lightGrey};
      }
    `
    

    How would I check for a style rule on label or .placeholder?

    enhancement 
    opened by duro 14
  • Doesn't work with jsdom

    Doesn't work with jsdom

    Enzyme uses jsdom environment to be able to mount components. The following error is thrown by this module.

    TypeError: Cannot read property 'cssRules' of undefined

    Thank you!

    opened by lgraziani2712 14
  • Bump decode-uri-component from 0.2.0 to 0.2.2

    Bump decode-uri-component from 0.2.0 to 0.2.2

    Bumps decode-uri-component from 0.2.0 to 0.2.2.

    Release notes

    Sourced from decode-uri-component's releases.

    v0.2.2

    • Prevent overwriting previously decoded tokens 980e0bf

    https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.1...v0.2.2

    v0.2.1

    • Switch to GitHub workflows 76abc93
    • Fix issue where decode throws - fixes #6 746ca5d
    • Update license (#1) 486d7e2
    • Tidelift tasks a650457
    • Meta tweaks 66e1c28

    https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.0...v0.2.1

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Not working correctly with @testing-library/react

    Not working correctly with @testing-library/react

    I'm trying to use this library with @testing-library/react and can't make it work properly. I changed package versions, looked on other github repositories and impossible to find a working example. (Does anyone has a working repo to show ?)

    package.json

      "@swc/core": "^1.3.21",
      "@swc/jest": "^0.2.23",
      "@testing-library/jest-dom": "^5.16.5",
      "@testing-library/react": "^12.1.2",
      "@testing-library/user-event": "^13.5.0",
      "@types/jest": "^27.0.0",
      "@types/react": "^17.0.38",
      "@types/react-dom": "^17.0.11",
      "@types/styled-components": "^5.1.19",
      "jest": "^27.0.0",
      "jest-styled-components": "^7.1.1",
      "react": "^17.0.2",
      "react-dom": "^17.0.2",
      "styled-components": "^5.0.0",
      "typescript": "^4.5.4"
    

    test file

    import React from 'react';
    import { render, screen } from '@testing-library/react';
    import styled from 'styled-components';
    import '@testing-library/jest-dom/extend-expect';
    import 'jest-styled-components';
    
    const Button = styled.button`
      color: yellow;
    `;
    
    describe.only('Test', () => {
      it('works', () => {
        const { container } = render(<Button />);
        expect(container.firstChild).toMatchSnapshot();
      });
    });
    

    snapshot:

    // Jest Snapshot v1, https://goo.gl/fbAQLP
    
    exports[`Test works 1`] = `
    <button
      class="hJBeEn"
    />
    `;
    

    jest.config.js

    module.exports = {
      roots: ['<rootDir>/src'],
      collectCoverageFrom: [
        'src/**/*.{js,jsx,ts,tsx}',
        '!src/**/*.d.ts',
        '!src/mocks/**',
      ],
      coveragePathIgnorePatterns: [],
      testEnvironment: 'jsdom',
      modulePaths: ['<rootDir>/src'],
      transform: {
        '^.+\\.(ts|js|tsx|jsx)$': '@swc/jest',
        '^.+\\.css$': '<rootDir>/config/jest/cssTransform.js',
      },
      modulePaths: ['<rootDir>/src'],
      // testRunner: "jest-jasmine2" // I tried with default and jest-jasmine2
    };
    

    cssTransform.js

    module.exports = {
      process() {
        return 'module.exports = {};';
      },
      getCacheKey() {
        return 'cssTransform';
      },
    };
    
    opened by balibou 0
  • More diffs showing on unchanged snapshot lines

    More diffs showing on unchanged snapshot lines

    Came up while upgrading jest-styled-components | 7.0.8 -> 7.1.1

    possibly related to #355 ( and in turn #419 ).

    It seems as though what once were separate lines, became one.

    e.g.

         .c1 button,
       - .c1 html input[type="button"],
       - .c1 input[type="reset"],
       - .c1 input[type="submit"] {
       + .c1 html input[type="button"],.c1 input[type="reset"],.c1 input[type="submi…
           -webkit-appearance: button;
           cursor: pointer;
           *overflow: visible;
         }
    

         .c1 html input[disabled] {
           cursor: default;
         }
         
       - .c1 input[type="checkbox"],
       - .c1 input[type="radio"] {
       + .c1 input[type="checkbox"],.c1 input[type="radio"] {
           box-sizing: border-box;
           padding: 0;
           *height: 13px;
           *width: 13px;
    

    opened by virtuoushub 0
  • [Bug] Chained selectors with pseudo-state filters are parsed incorrectly in v7.1.1

    [Bug] Chained selectors with pseudo-state filters are parsed incorrectly in v7.1.1

    Problem

    In v7.1.1, Jest-styled-components replaced css dependency to @adobe/css-tools. There is a bug in @adobe/css-tools where its parses chained selectors incorrectly. Chained selectors with psuedo-states are parsed incorrectly.

    For example

    export const StyledButton = styled('button')`
      color: white;
      padding: 40px;
      background: black;
    
      &[data-focus-visible-added]:not(:disabled),
      &:focus-visible:not(:disabled) {
        background: red;
        box-shadow: green;
      }
    `;
    
    

    Before the update, css would parse the rule as two selectors

        {
            type: 'rule',
            selectors: [
              '.fNulUe[data-focus-visible-added]:not(:disabled)',
              '.fNulUe:focus-visible:not(:disabled)'
            ],
            declarations: [ [Object], [Object] ],
            position: { start: [Object], end: [Object], source: '' }
        },
    

    After the update, @adobe/css-tools would parse the rule as one selector

        {
            type: 'rule',
            selectors: [
                '.fNulUe[data-focus-visible-added]:not(:disabled),.fNulUe:focus-visible:not(:disabled)'
            ],
            declarations: [ [Object], [Object] ],
            position: { start: [Object], end: [Object], source: '' }
        },
    

    This would result in an error where it can't find the selector with toHaveStyleRule()

       No style rules found on passed Component using options:
        {"modifier":"&:focus-visible:not(:disabled)"}
    
          18 |
          19 |     await expect(myButton).toHaveFocus();
        > 20 |     await expect(myButton).toHaveStyleRule("box-shadow", "green", {
             |                            ^
          21 |       modifier: "&:focus-visible:not(:disabled)",
          22 |     });
          23 |   });
    
    

    How to debug

    In node_modules/jest-styled-components/src/toHaveStyleRule.js , add a console.log in getRules()

    const getRules = (ast, classNames, options) => {
      const rules = (hasAtRule(options) ? getAtRules(ast, options) : ast.stylesheet.rules).map((rule) => ({
        ...rule,
        selectors: Array.isArray(rule.selectors) ? rule.selectors.map(normalizeQuotations) : rule.selectors,
      }));
      console.log(rules)
      return rules.filter((rule) => rule.type === 'rule' && hasClassNames(classNames, rule.selectors, options));
    };
    

    Link to barebone repo

    opened by endpoint-vtsang 1
  • tabs vs spaces

    tabs vs spaces

    Hi, for some reason, only on CI, some of my snapshots error out and show a diff that looks identical to the original.

    The only difference is that the proposed change uses tabs while the stored snapshot uses spaces.

    Do you have any idea of why this could happen? I'm on Jest 27 if it matters.

    opened by FezVrasta 0
Releases(v7.1.1)
  • v7.1.1(Aug 31, 2022)

    What's Changed

    • Fix diff on unchanged by @cincodenada in https://github.com/styled-components/jest-styled-components/pull/419

    New Contributors

    • @cincodenada made their first contribution in https://github.com/styled-components/jest-styled-components/pull/419

    Full Changelog: https://github.com/styled-components/jest-styled-components/compare/v7.1.0...v7.1.1

    Source code(tar.gz)
    Source code(zip)
  • v7.1.0(Aug 9, 2022)

    What's Changed

    • Use @adobe/css-tools (maintained) instead of css (unmaintained) by @holblin in https://github.com/styled-components/jest-styled-components/pull/416
    • perf(utils): only extract HTML once during while loop by @me4502 in https://github.com/styled-components/jest-styled-components/pull/413
    • Bump plist from 3.0.4 to 3.0.6 by @dependabot in https://github.com/styled-components/jest-styled-components/pull/418
    • Bump ansi-regex from 4.1.0 to 4.1.1 by @dependabot in https://github.com/styled-components/jest-styled-components/pull/417
    • Bump semver-regex from 3.1.3 to 3.1.4 by @dependabot in https://github.com/styled-components/jest-styled-components/pull/411
    • Bump minimist from 1.2.5 to 1.2.6 by @dependabot in https://github.com/styled-components/jest-styled-components/pull/408
    • Bump async from 2.6.3 to 2.6.4 by @dependabot in https://github.com/styled-components/jest-styled-components/pull/409
    • Bump node-fetch from 2.6.6 to 2.6.7 by @dependabot in https://github.com/styled-components/jest-styled-components/pull/412
    • Fix issue #403 with snake case filenames by @kamaltmo in https://github.com/styled-components/jest-styled-components/pull/404
    • fix: use correct repository syntax by @dunklesToast in https://github.com/styled-components/jest-styled-components/pull/402
    • Bump simple-plist from 1.3.0 to 1.3.1 by @dependabot in https://github.com/styled-components/jest-styled-components/pull/410

    New Contributors

    • @holblin made their first contribution in https://github.com/styled-components/jest-styled-components/pull/416
    • @me4502 made their first contribution in https://github.com/styled-components/jest-styled-components/pull/413
    • @kamaltmo made their first contribution in https://github.com/styled-components/jest-styled-components/pull/404
    • @dunklesToast made their first contribution in https://github.com/styled-components/jest-styled-components/pull/402

    Full Changelog: https://github.com/styled-components/jest-styled-components/compare/v7.0.8...v7.1.0

    Source code(tar.gz)
    Source code(zip)
  • v7.0.8(Nov 22, 2021)

    What's changed

    • fix detection of classnames when babel plugin is involved (9ba77538b6d352a6c40d2c2505da8dbbbcecbb51)

    Full Changelog: https://github.com/styled-components/jest-styled-components/compare/v7.0.7...v7.0.8

    Source code(tar.gz)
    Source code(zip)
  • v7.0.7(Nov 21, 2021)

    What's Changed

    • Fix issue #317 by @marcosvega91 in https://github.com/styled-components/jest-styled-components/pull/319
    • fix: incorrect negated assertion for rule existence check by @noahnu in https://github.com/styled-components/jest-styled-components/pull/345
    • Fix native toHaveStyleRule to work with object style props by @sayav in https://github.com/styled-components/jest-styled-components/pull/337
    • Make the global installation clearer by @RobinKnipe in https://github.com/styled-components/jest-styled-components/pull/323

    New Contributors

    • @marcosvega91 made their first contribution in https://github.com/styled-components/jest-styled-components/pull/319
    • @noahnu made their first contribution in https://github.com/styled-components/jest-styled-components/pull/345
    • @sayav made their first contribution in https://github.com/styled-components/jest-styled-components/pull/337
    • @RobinKnipe made their first contribution in https://github.com/styled-components/jest-styled-components/pull/323

    Full Changelog: https://github.com/styled-components/jest-styled-components/compare/v7.0.6...v7.0.7

    Source code(tar.gz)
    Source code(zip)
  • v7.0.6(Nov 9, 2021)

    • Fix false negative detection of some media queries by simplifying media query regex for stripping spaces (#379)
    • Improve test and memory utilization by removing sc style nodes on cleanup (#382)
    • Add snapshot options to customize what CSS is included in jest snapshots (#375)
    • Fix type error when using css ttl with "modifier" option (#367)
    • Add example of how to handle override styles to README.md (#372)
    Source code(tar.gz)
    Source code(zip)
  • v7.0.5(Jul 9, 2021)

    • dependency upgrades to resolve some security warnings and such
    • Strip css rules belonging to unused styled components referenced by another (#351)
    • added explicit node >= 12 "engines" field (we have been using Array.flatMap which requires at least v11, so picked the closest LTS afterward)
    Source code(tar.gz)
    Source code(zip)
  • v7.0.4(Apr 18, 2021)

  • v7.0.3(Aug 19, 2020)

    • Strip static class names from jest snapshot results (#320) thanks @blnoonan
    • Fix get styled className from children components (#313) thanks @vxcamiloxv
    Source code(tar.gz)
    Source code(zip)
  • v7.0.2(Apr 9, 2020)

  • v7.0.1(Apr 7, 2020)

    • Update Matchers interface (#269) thanks @tobilen

    • Extend global namespace with jest matcher (#308) thanks @tobilen

    • support shallow rendering when nesting styled components (#306) (#309) thanks @functionalDev

    • Remove object spread to continue Node LTS 10/12 support (#304) thanks @vxcamiloxv

    Source code(tar.gz)
    Source code(zip)
  • v7.0.0(Jan 13, 2020)

  • v7.0.0-beta.2(Nov 12, 2019)

  • v6.3.4(Nov 12, 2019)

  • v7.0.0-beta.1(Jun 15, 2019)

  • v6.3.3(Jun 15, 2019)

  • v7.0.0-beta.0(Jun 14, 2019)

Owner
styled-components
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
styled-components
Typograpy components for react and styled-components

styled-typography Typograpy components for react and styled-components styled-typography is a small set of components, using styled-components, to bet

Mike Engel 125 Nov 30, 2022
Imersão React.js 3º edição. Project using ReactJS, Next JS, and Styled Components for the week challenge by Alura. We created a social network inspired by Orkut.

Example app with styled-components This example features how you use a different styling solution than styled-jsx that also supports universal styles.

Julie 5 Jul 19, 2021
Minimal and performant React component library built on styled-components

Minimal and performant React component library built on styled-components

Cody Nova 0 Jan 3, 2022
Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utilizando Styled Components

Simple Styled Form Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utiliza

Lucas Klein 1 Oct 29, 2021
The simplest solution for content loading in React and styled-components.

styled-content-loader The simplest solution for content loading in React and styled-components. Getting Started npm install styled-components styled-c

Rafael Franco 14 Dec 7, 2022
Simple Portfolio Using React Hooks & Styled Components

Said MOUNAIM To view a live example, click here. Getting Started These instructi

Said Mounaim 6 Jun 28, 2022
Front-End Mentor: Landing page usando ReactJS + Styled Components

Front-End Mentor: Fylo Landing Page ✨ O projeto se trata de um desafio disponível no site Front-End Mentor. A ideia é desenvolver um código que se apr

Larissa Oliveira 8 Feb 14, 2022
🎥A criação de uma UI para Streaming utilizando React.js, Styled Components junto com Sass.

Movie Screen - Exercitando React, Styled Components e Sass ??️ Dependencias React Styled Components Sass React Icons ?? Objetivo O principal intuito d

Fábio de Andrade 1 Dec 28, 2021
Styled Components for React Native the way they should have been.

?? Styled-RN Styled Components for React Native the way they should have been. Inspired by this article Intro Why ?? styled-rn it better than ???? sty

Vels Lobak 23 Jul 31, 2022
A react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

fork-me-corner is a react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

Victor Dantas 9 Jun 30, 2022
Flexibly styled chat-widget for your react apps.

Flexibly styled chat-widget for your react apps. It was mainly created for integration with chat-bots in messengers.

Eddie Nubes 4 Nov 5, 2022
A styled switch for React built using Emotion CSS and Framer motion

A styled switch for React built using Emotion CSS and Framer motion

Haider Alshamma 7 Aug 27, 2021
A terminal style/styled portfolio website made with <3 using react.

A Terminal Styled Portfolio Website. ??‍??, a terminal style/styled portfolio website made with <3 using react.

ashish 67 Nov 22, 2022
This is a pre-styled React component for showcasing a GitHub user's projects. With Axios for API calls and Tailwind for styling, this component makes it easy to present your projects in a clean and professional manner

MyGitHub The MyGitHub component is a pre-styled React component for displaying a GitHub user's projects and other informations. With just one import,

Amos Kyalo 4 Feb 12, 2023
Seamless mapping of class names to CSS modules inside of React components.

React CSS Modules React CSS Modules implement automatic mapping of CSS modules. Every CSS class is assigned a local-scoped identifier with a global un

Gajus Kuizinas 5.3k Dec 28, 2022
Style your React components with simplicity using css inside your comments.

Style your React components with simplicity using css inside your comments.

Charly Albin 1 Oct 12, 2021
Encapsulated styling for your javascript components with all the power of javascript and CSS combined.

Stilr Encapsulated styling for your javascript components with all the power of javascript and CSS combined. Unique class names (Content Hash Based) U

kodyl 236 Nov 18, 2022
Incredible fast template toolkit for making new or re-styling existing components with Tailwind CSS.

Stail Incredible fast template toolkit for making new or re-styling existing components with Tailwind CSS. Why it's needed? First of all, I'm tired fr

null 6 Dec 8, 2022
Vite plugin that emulates Scoped CSS for React components

vite-react-css Vite plugin that emulates Scoped CSS for React components (using generated class names) Compatible with SSR Automatic code-splitting Ho

all oc 6 Aug 29, 2022