GithubHelp home page GithubHelp logo

jest-styled-components's Introduction

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

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

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. For Example: import the library once in the src/setupTests.js as follows:

import 'jest-styled-components'

...then add the following to test.config.js:

  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js']

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.

jest-styled-components's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jest-styled-components's Issues

pretty-format plugin not found

  Test suite failed to run

    Cannot find module 'pretty-format/build/plugins/ReactTestComponent' from 'serializer.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:151:17)
      at Object.<anonymous> (node_modules/jest-styled-components/src/serializer.js:2:25)
      at Object.<anonymous> (node_modules/jest-styled-components/src/index.js:2:20)

Changelog?

Hello, thanks for reading.

Just wondering if you have a changelog? I couldn't find one but perhaps you keep it somewhere I have not looked.

Thanks!

shared __snapshots__ on repo

This is a question.

When I switch to a team member's branch, then run test all snapshot test fail, after passing locally. Though looking at the error it is just the class hash that's changed. Should we be including or not including snapshots to not be getting errors while using jest-styled-component for snapshots? or are we missusing jest-styled-components

No placeholder classes generated

While using the library, it seems all the classes on the component are replaced by an empty string, those created by StyledComponents as well as any other.

image

Package.json

    "enzyme-to-json": "^1.5.1",
    "jest-styled-components": "^4.0.2",

Test file

import 'jest-styled-components';
import toJson from 'enzyme-to-json';

...

    const container = shallow(<MyComponent></MyComponent>);
    expect(toJson(container)).toMatchSnapshot();

Typescript support

Hi, can you offer support for typescript? I am getting this error when I use toMatchStyledComponentsSnapshot "[ts] Property 'toMatchStyledComponentsSnapshot' does not exist on type 'Matchers'."

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!

Doesn't work

import * as React from 'react';
import styled from 'styled-components';
import { shallow } from 'enzyme';
import 'jest-styled-components';

const Wrapper = styled.div`
  button {
    color: red;
  }
`;

const Button = (props) => {
  return (
    <Wrapper>
      <button>hello</button>
    </Wrapper>
  );
}

describe('<Button>', () => {
  describe('rendering', () => {
    it('renders correctly', () => {
      const wrapper = shallow(<Button />);
      expect(wrapper).toMatchSnapshot();
    });
  });
});
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`<Button> props.children renders correctly 1`] = `
<styled.div>
  <button>
    label
  </button>
</styled.div>
`;

This is my jest.config.js

module.exports = {
  globals: {
    "ts-jest": {
      tsConfigFile: 'tsconfig.json'
    },
  },
  moduleFileExtensions: ['tsx', 'ts', 'js'],
  transform: {
    '^.+\\.(ts|tsx)$': './node_modules/ts-jest/preprocessor.js',
    '^.+\\.(s?css|less)$': './node_modules/jest-css-modules',
  },
  testMatch: ['**/test.(ts|tsx)'],
  testEnvironment: 'node',
  snapshotSerializers: ['enzyme-to-json/serializer'],
  collectCoverage: true,
  mapCoverage: true,
  coverageDirectory: '.coverage'
};

Sometimes getClassNames throws error

I've been using some of my own code to test styles on styled-components v1 before, now migrating to v2 and came across this library. As far, Migrating test and I really like it. ๐Ÿ‘ But I went into this issue.

With reference with this line of code in getClassNames function
https://github.com/styled-components/jest-styled-components/blob/master/src/toHaveStyleRule.js#L11

Using .find('[className]').first().prop('className') sometimes throw an error. It cannot find that node.

screen shot 2017-07-20 at 3 58 36 pm

For example in the test suite I send in the component to match styles like
expect(wrapper.find('TabButtonGroup')).toHaveStyleRule('background-color', baseColors.capecod)

I understand that we already sent in a wrapper to find something to retrieve styles. Why it would perform another to find children that contains classnames?

From my utility, I've using go get classnames from enzyme selectors by reading generatedClassName property in the component state.
Then it should get the classname by received.getNode().state.generatedClassName
I tried and it could get by using this code.

I test and the different is the getting by props as in the current codebase has combined classnames if there are overrides? May be is it for this benefit?

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.

styled-components/styled-components#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)

toHaveStyleRule pseudo classes support

I like using toHaveStyleRule more than using snapshots for testing. I was running tests that includes assertions of media queries. But found out that the code doesn't includes rules from media queries. So I modified to get it working adding a function to get it like

// toHaveStyleRule.js
...
const getMediaRules = (ast, classNames) => {
  return ast.stylesheet.rules
    .filter(rule => rule.type === 'media')
    .map(rule => rule.rules)
    .reduce((a, b) => a.concat(b), [])
    .filter(rule => hasClassNames(classNames, rule.selectors))
}

...
// in toHaveStyleRule()
const mediaRules = getMediaRules(ast, classNames)
const rules = getRules(ast, classNames).concat(mediaRules)

I could get it up and running as for now, but a new problem arises. It combines the rules so ordering has effect. The last one is the one that will be matched. (The picture shows the same property rule but different media queries.)

screen shot 2017-07-20 at 3 44 29 pm

Would it be better for testing media queries styles with an options api like

expect(component).toHaveStyleRule('margin', '50px', {media: {'max-width': '768px'}})

and match style within rules of that media query only?
If interested and have any comments how the api should call, I will try to work on and submit PR. ๐Ÿ‘

Can't import chai's expect

Hi there! I'm having a problem where I'm not able to import chai's expect to make assertions

import renderer from 'react-test-renderer'
import 'jest-styled-components'
import styled from 'styled-components'
import { expect } from 'chai'

describe('view', () => {
  it('should render break for newline character', () => {
    const StyledDiv = styled.div`
      color: red;
    `

    const tree = renderer.create(<StyledDiv />).toJSON()
    expect(tree).toHaveStyleRule('color', 'red')

  })
})

// Invalid Chai property: toHaveStyleRule 
//      at Error (native)

If I had to guess, I think it's that this module modifies the expect global, which is overriden by importing chai. Note that the above error can be fixed if you import chai's expect with an alias. You would then use the alias for assertions where you want chai's API and the normal expect for styled-components assertions

import { expect as chaiExpect } from 'chai'

Given that this is the officially supported module for testing, it would be great if it could be used with chai! What I'm imagining is maybe a way to register it as a chai plugin similar to what chai-enzyme does. There would perhaps also be some work required to be sure the API matches what chai expects.

Let me know if this is something you would like to support, I'm willing to help! ๐Ÿ™‚

CSS Properties are duplicated in snapshot when using styled(...) syntax.

Hi again.

This time I think I have a real bug. Promise :).

When using styled(...) to override the styles on a component the CSS properties overridden are duplicated in the snapshot produced. The example below should illustrate this:

/**
 * @jest-environment node
 */

import React from 'react'
import styled from 'styled-components'
import renderer from 'react-test-renderer'
import { shallow } from 'enzyme'
import 'jest-styled-components';

const Button = styled.button`
  background: palevioletred;
  border-radius: 3px;
  border: none;
  color: white;
`

const TomatoButton = styled(Button)`
  background: tomato;
`

test('enzyme', () => {
  const tree = shallow(
    <TomatoButton>
      Hello World!
    </TomatoButton>,
  )

  expect(tree).toMatchStyledComponentsSnapshot()
})

test('react-test-renderer', () => {
  const tree = renderer
    .create(
      <TomatoButton>
        Hello World!
      </TomatoButton>,
    )
    .toJSON()

  expect(tree).toMatchStyledComponentsSnapshot()
})

Produces the snapshots:

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`enzyme 1`] = `
.jUiOOZ {
  background: palevioletred;
  border-radius: 3px;
  border: none;
  color: white;
  background: tomato;
}

<button
  className="jUiOOZ"
>
  Hello World!
</button>
`;

exports[`react-test-renderer 1`] = `
.jUiOOZ {
  background: palevioletred;
  border-radius: 3px;
  border: none;
  color: white;
  background: tomato;
}

<button
  className="jUiOOZ"
>
  Hello World!
</button>
`;

Note the duplication of the background property. It seems it's actually easy enough to follow and the latter property is the one that will actually be present on the class.

I'm starting to see if I can work out where this can be fixed now.

Thanks!

Tyler

Ava support?

Hi,
First thanks for this project. It seem to be the only way now to test styled components.
I was wondering if there is any chance that you guys could support ava as well?

Enzyme shallow with toMatchStyledComponentsSnapshot

Hey!

I'm just trying out your module. I'm running into something strange. Basically, I'm not getting the same results you showed in the preview screenshot.

The toMatchStyledComponentsSnapshot generates a snapshot that doesn't contain the detailed styles of the class.

The documentation being a bit short, am I doing something wrong here?

const MyStyledComponent = styled.div`
  background-color: rgba(0, 0, 0, 0.3);
  width: 100%;
  height: 8px;
  border-radius: 4px;
  margin: 6px 0;
`;

The test:

let wrapper;
beforeEach(() => {
  wrapper = shallow(<MyStyledComponent {...props} />);
});

it('should match the snapshot', () => {
  expect(wrapper).toMatchStyledComponentsSnapshot();
});

Snapshot result:

exports[`should match the snapshot 1`] = `
ShallowWrapper {
  ...
}...

When mount(..) the component and using toHaveStyleRule I get Cannot read property 'styleSheet' of undefined.

Thanks!

Versions in use:

jest: v20.0.4
styled-components: v1.4.6
jest-styled-components: v2.1.1
enzyme: v2.8.2

Snapshots donยดt include @supports at-rules

Hi there,

I need to add snapshot tests for styled components which include @supports at-rules.

const Container = styled.div`
	display: flex;
	flex-wrap: wrap;
	@supports (display: grid) {
		display: grid;
		grid-auto-flow: row;
		justify-content: start;
	}
`;

But unfortunately the snapshots donยดt include the @supports CSS at-rules.

exports[`Container should render correctly 1`] = `
.kpwVYx {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

<div
  className="sc-bdVaJa kpwVYx"
/>
`;

Are you already aware of this issue?

Cheers,
Olaf

toHaveStyleRule TypeError: Cannot read property '1' of null

I'm trying to test whether the component has display:inline when horizontal is set to true.
Here is the component code:

export const StyledLabel = styled.label`
  display: block;
  ${props => props.horizontal && css`
      display: inline;
  `}
  & i {
    color: red;
  }
  ${props => props.css}
`;

And here is the test:

import { StyledLabel } from "./Label";
import React from "react";
import { mount } from "enzyme";

test("when horizontal must be display:inline", () => {
  //given
  const text = "text";
  //when
  const component = mount(<StyledLabel horizontal>{text}</StyledLabel>);
  //then
  expect(component).toHaveStyleRule("display", "inline");
});

But at the end I got an error:

 FAIL  src\components\Label\index.test.js
  โ— <Label /> โ€บ when horizontal must be display:inline

    TypeError: Cannot read property '1' of null

      at message (node_modules/jest-styled-components/src/matchers/toHaveStyleRule.js:79:48)
      at Object.it (src/components/Label/index.test.js:73:23)
          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:169:7)

I have "jest-styled-components": "^3.0.0" and "styled-components": "^2.0.0" and latest CRA.

Please improve documentation

I am having a lot of trouble understanding the documentation of jest-styled-components, for example:

  1. what is tree, how was tree generated in the examples?
expect(tree).toHaveStyleRule(property, value)

I only found out after looking at the docs of react-test-renderer for generating snapshots that I would have to use it to generate the tree.

  1. which version of styled-components do you support and do you need me to import the babel-plugin?

I read in the issue #29 and I decided to include it anyways.

  1. How can I test styles for nested components using haveStyleRule such as
styled(MyComponent)`
   > .a .b {
      display: ${props => props.a ? inline: block}; 
  }
`

I ended up using snapshots to test the component

Error returned when using toHaveStyleRule

Hi, I'm hoping someone can help me with a problem I'm having with my tests.

Each time I run the following test:

import React from 'react';
import { shallow } from 'enzyme';
import 'jest-styled-components';

import CreateButton from './';
import LinkButton from './CreateButton.styles';

describe('CreateButton', () => {
  const stateKey = 'create';
  const navigationData = { client: 'client' };
  const text = 'Create Campaign';
  const color = 'red';
  let component;

  beforeEach(() => {
    component = shallow(
      <CreateButton
        stateKey={stateKey}
        navigationData={navigationData}
        text={text}
      />
    );
  });

  it('should render correctly', () => {
    expect(component).toMatchSnapshot();
  });

  it('should have a LinkButton component', () => {
    expect(component.find(LinkButton)).toHaveLength(1);
  });

  it('should have correct Text component', () => {
    const props = component.find(LinkButton).props();
    expect(props.stateKey).toBe(stateKey);
    expect(props.navigationData).toBe(navigationData);
    expect(props.text).toBe(text);
  });

  it('should display the correct colour', () => {
    component = shallow(
      <LinkButton
        stateKey={stateKey}
        navigationData={navigationData}
        text={text}
        theme={{ buttonText: color }}
      />
    );
    expect(component).toMatchStyledComponentsSnapshot();
    expect(component).toHaveStyleRule('color', color);
  });
});

I receive this error:

  โ— CreateButton โ€บ should display the correct colour

    
            "Expected [object Object] to be a component from react-test-renderer, or a mounted enzyme component."
    
            "But had an error, TypeError: Cannot read property '_renderedComponent' of undefined"
      
            
      at Object.<anonymous> (src/components/CreateButton/CreateButton.tests.js:50:23)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at process._tickCallback (internal/process/next_tick.js:109:7)

Here's what the component I'm attempting to test looks like:

import styled from 'styled-components';

import { LinkButton } from 'tetris-blocks';

export default styled(LinkButton)`
  width: 170px;
  height: 40px;
  font-size: 0.95em;
  color: ${({ theme }) => theme.buttonText};
`;

Please also see the snapshot file I'm using below:

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`CreateButton should display the correct colour 1`] = `
.iHrtRh {
  width: 170px;
  height: 40px;
  font-size: 0.95em;
  color: red;
}

<LinkButton
  className="sc-htpNat iHrtRh"
  navigationData={
    Object {
      "client": "client",
    }
  }
  stateKey="create"
  text="Create Campaign"
  theme={
    Object {
      "buttonText": "red",
    }
  }
/>
`;

exports[`CreateButton should render correctly 1`] = `
<Styled(LinkButton)
  navigationData={
    Object {
      "client": "client",
    }
  }
  stateKey="create"
  text="Create Campaign"
/>
`;

A couple of us have reviewed this now and can't reach a conclusion as to what's causing the problem, but after commenting out the following expect(component).toHaveStyleRule('color', color); from the test it passes. Which has led us to believe there could be a problem with the package.

I'm using currently using version 3.0.2 of the package.

Many thanks and apologies for all the code snippets!

Jest snapshot testing passing unique classNames

Moved form styled-components/styled-components#916 by @corbanbrook

Styled components generate a unique classname hash based on the style content and passes this classname to the snapshot. This causes snapshots to break when styles are adjusted.

I understand this might be useful if you want to break snapshots on style change or even show style diffs with the jest-styled-components plugin but by including the hashed classname it ends up not only breaking the snapshot of the changed component but also the snapshots of any components that wrap it. This can be a mild annoyance when adjusting a Button styling causes hundreds of snapshots all over the application to break because they included Button.

CSS Modules had a similar issue but solved it with the identity-obj-proxy lib and moduleNameMapper:

"moduleNameMapper": {
  "\\.(css)$": "identity-obj-proxy"
 }

which would convert className={styles.myStyle} to className="myStyle" in the snapshot rather than "myStyle-{unique-hash}".

Is there something similar for mocking in classnames for styled-components?

snapshot parse errors

It seems the new 2+ versions of this package are snapshotting incorrectly ( just a load of c0 etc )

Tests:

import React from 'react'
import renderer from 'react-test-renderer'
import withTheme from '~/config/jest/jestTheme'
import 'jest-enzyme'
import 'jest-styled-components'
import { mount } from 'enzyme'

import { CardTitle } from '../'

describe('Component: Card Title', () => {
  it('should render without props.route', () => {
    let component = withTheme(<CardTitle title="title testing" />)

    const tree = renderer.create(component).toJSON()
    expect(tree).toMatchSnapshot()
  })

  it('should render the Link if props.href is supplied or inherited', () => {
    const component = mount(
      withTheme(<CardTitle href="/link" title="title testing" />)
    )

    expect(component.find('Link').length).toBe(1)
  })
})

Snapshot created:

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Component: Card Title should render without props.route 1`] = `
c0.c0bc0pc0Dc0Oc0ec0Uc0 c0{c0
c0 c0 c0fc0oc0nc0tc0-c0wc0ec0ic0gc0hc0tc0:c0 c0bc0oc0lc0dc0;c0
c0 c0 c0lc0ic0nc0ec0-c0hc0ec0ic0gc0hc0tc0:c0 c01c0.c03c0;c0
c0 c0 c0fc0oc0nc0tc0-c0sc0ic0zc0ec0:c0 c01c06c0pc0xc0;c0
c0 c0 c0cc0oc0lc0oc0rc0:c0 c0#c0fc0fc0fc0fc0fc0fc0;c0
c0}c0
c0
c0<c0dc0ic0vc0
c0 c0 c0cc0lc0ac0sc0sc0Nc0ac0mc0ec0=c0"c0cc0ac0rc0dc0-c0tc0ic0tc0lc0ec0 c0 c0dc03c0qc01c0yc07c0-c00c0 c0bc0pc0Dc0Oc0ec0Uc0"c0
c0>c0
c0 c0 c0tc0ic0tc0lc0ec0 c0tc0ec0sc0tc0ic0nc0gc0
c0<c0/c0dc0ic0vc0>c0
`;

Component:

import React from 'react'
import { string, node, bool } from 'prop-types'
import LinkAnchor from '~/components/LinkAnchor'

import StyledCardHeader from './CardHeader.styles'

const CardHeader = props => {
  let header = (
    <StyledCardHeader
      href={props.href}
      src={props.src}
      top={props.top}
      bottom={props.bottom}
      height={props.height}>
      {props.children}
    </StyledCardHeader>
  )

  if (props.href) {
    header = (
      <LinkAnchor href={props.href}>
        {header}
      </LinkAnchor>
    )
  }

  return header
}

CardHeader.propTypes = {
  href: string,
  src: string,
  height: string,
  top: bool,
  bottom: bool,
  children: node
}

CardHeader.defaultProps = {
  top: false,
  bottom: false
}

export default CardHeader

Styles:

import styled from 'styled-components'

const StyledCardHeader = styled.header`
  background-repeat: no-repeat;
  background-position: center center;
  background-color: ${props => props.theme.colors.itemBackground};
  background-size: cover;

  ${props =>
    props.src &&
    `
    background-image: url('${props.src}');
    min-height: ${props.height || '200px'};
    `};

  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: ${props => (props.bottom ? 'flex-end' : 'flex-start')};
  padding: ${props => props.theme.grid.quarterSpacing};
  color: ${props => props.theme.colors.white};
`

export default StyledCardHeader

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.

No feedback on what has changed for nested components

Tried and it works great. Just for nested components I do not get any feedback on what changed.

That's the component: I want to build a <ButtonGroup />.
image

However, the only feedback I get through snapshot testing is that something inside the styled-component has changed - no feedback whatsoever on what has changed. Is there a way to have feedback also on nested components?

image

Problems with testEnvironment "node"

I'm barerly sure that I'm not the only one who is using jest with the default test environment which is "jsdom" for jest.

So I love this library, it works very well with the v2.0 but changing my testEnvironment to node just broke my tests. Because in my project I have access to the DOM global variables and the testEnvironment: jsdom handles it very good.

So I would like to keep the consistency in my tests and the jsdom test environment instead of adding complex global definitions.

Is there a workaround for this?

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?

Tests pass when styles change on a nested component using enzyme shallow.

Hi @MicheleBertoli . First off, thanks for making this package - it looks like it could be super useful!

I'm really keen to get using jest-styled-components but have run into this issue. To reproduce:

  1. Clone jest-styled-components
  2. Change test/index.spec.js to remove the react-test-renderer test so that we don't get confused by test output.
  3. Change a style on the Title component.
  4. Re-run tests. Test still passes.

If we inspect the snapshot the nested Title component is serialised as a styled.h1 and there is no information about the styles that have been applied. I'd like to try help with this if I get a chance.

Thanks,

Tyler

Cannot simulate events with Enzyme

Using React Native, before I styled my components, I was able to run this code to simulate the toggling of switches:

const wrapper = shallow(
  <CameraSettings />,
  { context: { store: mockStore(initialState) } },
);
const render = wrapper.dive();
render.find('Switch').forEach(child => {
  child.simulate('valueChange');
});

Now with my styled-component, I am able to find the required children, but cannot seem to simulate the valueChange function anymore. (I simply replaced 'Switch' with 'Styled(Switch)' and the render.find was able to locate the correct elements.)

Any ideas how I can simulate events using Enzyme with styled-components? (More of a question than an issue, and I'll gladly move to stack overflow if you'd like, but figured if anyone knew they'd likely be looking here, not there).

Pull Request Details

Hi @MicheleBertoli,

First time I am making a PR in an open-source project and just wanted to know your expectations.

I added the React web toHaveStyle matcher. It's passing the linting and works as expected with Enzyme. I even added a bit of documentation to the Readme. I think I need to add comments to the code itself, and maybe change the anonymous arrow functions to declared functions to make it look like the rest of the code base.

Let me know what you think!

Thanks

Formating removed when updating snapshots

Hi @MicheleBertoli

I'm sorry this might not the fault of this project, but the names jest and styled-components have been giving me grief and I hoped you had maybe see this happening.

It seems to have something to do with the environment that the tests are running in. I'm using yarn, but encountering issues where a space character is getting removed:

screen shot 2017-07-28 at 6 05 10 pm

Same goes for urls that would be passed to a component. I can provide more details, just wondering if there's anything familiar that you might know is going on. Appreciate this project a lot!

CSS parser returns different values for matching

@MicheleBertoli ๐Ÿ˜ƒ

I encounter that I have 2 projects that installs the same jest-styled-components package but when running the same exact test the CSS parser returns different strings when matching rules.

This is what it should be expected. (Like test)
screen shot 2017-09-07 at 2 49 03 pm

Oops! This is not right, The space disappears.
screen shot 2017-09-07 at 2 49 21 pm

I inspect that the css parser version is the same. "version": "2.2.1"
What could be the causes of this? Or how should we handle it? ๐Ÿ˜‚

Trouble understanding toHaveStyleRule()

Hi,
I'm trying to use toHaveStyleRule but I'm unsure how to use it. My naive modification to jest-styled-components/test/index.spec.js is here:

test('react-test-renderer', () => {
  const tree = renderer.create(
    <Wrapper>
      <Title>Hello World, this is my first styled component!</Title>
    </Wrapper>,
  ).toJSON()

  expect(tree).toMatchStyledComponentsSnapshot()
  expect(tree).toHaveStyleRule('color', 'papayawhip');
})

test('enzyme', () => {
  const tree = shallow(
    <Wrapper>
      <Title>Hello World, this is my first styled component!</Title>
    </Wrapper>,
  )

  expect(tree).toMatchStyledComponentsSnapshot();
  expect(tree).toHaveStyleRule('color', 'papayawhip');
})

But it throws errors:

 FAIL  test/index.spec.js
  โ— react-test-renderer


            "Expected [object Object] to be a component from react-test-renderer, or a mounted enzyme component."

            "But had an error, TypeError: Cannot read property 'styleSheet' of undefined"


      at Object.<anonymous> (test/index.spec.js:45:16)
      at process._tickCallback (internal/process/next_tick.js:103:7)

  โ— enzyme


            "Expected [object Object] to be a component from react-test-renderer, or a mounted enzyme component."

            "But had an error, TypeError: Cannot read property '_renderedComponent' of undefined"


      at Object.<anonymous> (test/index.spec.js:56:16)
      at process._tickCallback (internal/process/next_tick.js:103:7)

  โœ“ snapshot on null (8ms)
  โœ• react-test-renderer (47ms)
  โœ• enzyme (13ms)

Any help would be great, Thanks

Question: Failure to change class names and odd CSS property names

I am running my tests via the addon for Storybook (Storyshots).

Some of my Snapshots started failing a few days after using jest-styled-components (have just upgraded to 4.3 and there is no change). I have noticed that it doesn't seem to be intercepting all of the styled components class names (since the hash has changed on some snapshots and is not getting converted to something like c0).

I have also noticed weird property names like wc0dth and posc0tc0on in the failure report. Is looks like a regex is incorrectly capturing property names and not class names:

    -.eBc0kCs {
    +.c0MWc0eg {
    +  wc0dth: 8px;
    +  posc0tc0on: absolute;
    +  bottom: 0;
    +  left: 0;
    +}
    +
    +.fc0NsQu {
       posc0tc0on: relatc0ve;
       left: 0;
       top: 0;
       bottom: 0;
       wc0dth: 8px;

Looking at the snapshot file I can also see things like:

<dc0v
  className="card-contac0ner"

Some of my snapshots do have correct class names e.g. c0, but I am yet to determine the differences between styled components that work and ones that don't.

I am currently trying to reproduce it outside of Storybook, but in the meantime, do you have any ideas or particular information that you require?

`className` with trailing space breaks output

Given the following component:

import React, { Component } from 'react';
import styled from 'styled-components';

class Test extends Component {
  render() {
    return <StyledTest className="foo ">Hello world</StyledTest>;
  }
}

const StyledTest = styled.div`color: red;`;

export default Test;

and the following test:

import React from 'react';
import Test from './Test';
import { mount } from 'enzyme';
import 'jest-styled-components';
import toJson from 'enzyme-to-json';

test('renders correctly', () => {
  const test = mount(<Test />);
  expect(toJson(test)).toMatchSnapshot();
});

The following snapshot is generated

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`renders correctly 1`] = `
c1cc10c1.c1cc10c1ec1cc10c1rc1cc10c1Wc1cc10c1Ec1cc10c1xc1cc10c1Gc1cc10c1 c1cc10c1{c1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1cc1cc10c1oc1cc10c1lc1cc10c1oc1cc10c1rc1cc10c1:c1cc10c1 c1cc10c1rc1cc10c1ec1cc10c1dc1cc10c1;c1cc10c1
c1cc10c1}c1cc10c1
c1cc10c1
c1cc10c1<c1cc10c1Tc1cc10c1ec1cc10c1sc1cc10c1tc1cc10c1>c1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1<c1cc10c1sc1cc10c1tc1cc10c1yc1cc10c1lc1cc10c1ec1cc10c1dc1cc10c1.c1cc10c1dc1cc10c1ic1cc10c1vc1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1cc1cc10c1lc1cc10c1ac1cc10c1sc1cc10c1sc1cc10c1Nc1cc10c1ac1cc10c1mc1cc10c1ec1cc10c1=c1cc10c1"c1cc10c1"c1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1>c1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1<c1cc10c1dc1cc10c1ic1cc10c1vc1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1cc1cc10c1lc1cc10c1ac1cc10c1sc1cc10c1sc1cc10c1Nc1cc10c1ac1cc10c1mc1cc10c1ec1cc10c1=c1cc10c1"c1cc10c1 c1cc10c1sc1cc10c1cc1cc10c1-c1cc10c1bc1cc10c1dc1cc10c1Vc1cc10c1ac1cc10c1Jc1cc10c1ac1cc10c1 c1cc10c1ec1cc10c1rc1cc10c1Wc1cc10c1Ec1cc10c1xc1cc10c1Gc1cc10c1"c1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1>c1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1Hc1cc10c1ec1cc10c1lc1cc10c1lc1cc10c1oc1cc10c1 c1cc10c1wc1cc10c1oc1cc10c1rc1cc10c1lc1cc10c1dc1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1 c1cc10c1<c1cc10c1/c1cc10c1dc1cc10c1ic1cc10c1vc1cc10c1>c1cc10c1
c1cc10c1 c1cc10c1 c1cc10c1<c1cc10c1/c1cc10c1sc1cc10c1tc1cc10c1yc1cc10c1lc1cc10c1ec1cc10c1dc1cc10c1.c1cc10c1dc1cc10c1ic1cc10c1vc1cc10c1>c1cc10c1
c1cc10c1<c1cc10c1/c1cc10c1Tc1cc10c1ec1cc10c1sc1cc10c1tc1cc10c1>c1cc10c1
`;

Note the space in the className of the component. I discovered this in a component that has a conditionally added class. I can solve the don't-end-with-a-space problem a handful of ways on my end, but this feels like something that probably would be considered a bug.

In larger components, this causes Jest to crash due to the absurdly long strings it generates.

Style rules are always included

Is it possible to have only the class names substituted?

It makes no sense to me to include all css rules in the snapshot.
I rather have explicit toHaveStyleRule checks for important changes.

  • Whenever i have a change in my theme-file i break all tests, all the time.
  • When i break all tests all the time i get lazy.
  • When i (or my coworkers) get lazy i press and hold-down U
  • This is very very very bad.

CSS classes duplicated and inserted inside tags with Jest 21

given

import React from 'react';
import styled from 'styled-components';
import { mount } from 'enzyme';
import toJson from 'enzyme-to-json';
import 'jest-styled-components';

const Text = styled.span`color: red;`;

test('renders', () => {
  expect(toJson(mount(<Text />))).toMatchSnapshot();
});

Jest 20 produces snapshot

exports[`renders 1`] = `
.c0 {
  color: red;
}

<Text-test__Text>
  <span
    className="c0"
  />
</Text-test__Text>
`;

Jest 21 produces snapshot

exports[`renders 1`] = `
.c0 {
  color: red;
}

<Text-test__Text>
  .c0 {
  color: red;
}

<span
    className="c0"
  />
</Text-test__Text>
`;

toHaveStyleRule didn't see changes to the styles by styled(Component)

I have this test:

  it("styles got updated by styled-components", () => {
    //given
    const Styled = styled(Label)`
      background-color: seagreen;
    `;
    //when
    const tree = mount(<Styled>label</Styled>);
    //then
    expect(tree.find(Styled)).toHaveStyleRule("background-color", "seagreen");
  });

And I have that component under test:

import React from "react";
import PT from "prop-types";
import styled, { css } from "styled-components";

const Label = ({ children, isRequired, ...rest }) =>
  children ? <label {...rest}>{children}{isRequired && <i>*</i>}</label> : null;

Label.propTypes = {
  /** Flag that will add red `*` in after the label */
  isRequired: PT.bool,
  /** Makes label to be inlined with input */
  horizontal: PT.bool,
  /** To override label styles when he is a part of other component */
  css: PT.array,
  className: PT.string
};

// language=SCSS prefix=dummy{ suffix=}
export const StyledLabel = styled(Label)`
  display: block;
  ${props => props.horizontal && css`
    display: inline;
  `}
  & i {
    color: red;
  }
  ${props => props.css}
`;

export default StyledLabel;

The result is weird:

 FAIL  src\components\atoms\Label\index.test.js
  โ— <Label /> โ€บ styles got updated by styled-components
            "Expected iobhyf to have background-color matching seagreen"
            "But received, display: block;"

In the same time tree.find(Label) gives

"Expected [object Object] to be a component from react-test-renderer, or a mounted enzyme component."
"But had an error, TypeError: Cannot read property 'generatedClassName' of null"

and tree.find('label') gives:

"Expected [object Object] to be a component from react-test-renderer, or a mounted enzyme component."
"But had an error, TypeError: Cannot read property '_renderedComponent' of undefined"

Snapshot looks like that:

exports[`<Label /> styles got updated by styled-components 1`] = `
.iobhyf {
  display: block;
}

.iobhyf i {
  color: red;
}

.hBRMHQ {
  background-color: seagreen;
}

<label
  className="sc-bwzfXH hBRMHQ sc-bdVaJa iobhyf"
>
  label
</label>
`;

I have styled-components 2.0.1 jest-styled-components 3.0.1 enzyme 2.8.2

Whitespace in media query expression is removed

I am trying to test a component that renders one or more media queries.

The query I'm rendering:

@media only all and (min-width: 600px) {
...
}

My test looks like this:

import React from 'react';
import renderer from 'react-test-renderer';
import { spanWidthAsCalcRule, mediaQuery } from 'utils/grid';
import { ThemeProvider } from 'styled-components';
import 'jest-styled-components';
import theme from 'config/theme.json';
import Column from './';

describe('Column', () => {
    test('it should span full width when span equals amount of columns in layout', () => {
        const tree = renderer.create(<ThemeProvider theme={theme}><Column span={{ xsmall: 4 }}>Here be content</Column></ThemeProvider>).toJSON();

        expect(tree).toMatchSnapshot();
        expect(tree).toHaveStyleRule('max-width', '100%', {
            media: mediaQuery('xsmall'),
        });
    });
});

The function mediaQuery('xsmall') renders said media query. The test, however, fails.
I found that the snapshot prints the media query as @media only all and (max-width:599px) instead of the expected @media only all and (max-width: 599px) (notice space between : and 599px.

broken snapshot value when className === tag name

Hi there! I think I may have found a bug. Given the following component:

import styled from 'styled-components';

const TextArea = styled.textarea.attrs({
  className: 'textarea',
  spellCheck: 'false'
})``;

export default TextArea;

And the following test:

import React from 'react';
import { shallow } from 'enzyme';
import TextInput from './TextInput';
import 'jest-styled-components';
import toJson from 'enzyme-to-json';

describe('TextInput', function() {
  test('renders', () => {
    const wrapper = shallow(<TextInput />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });
});

the following output will be generated:

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`TextArea renders 1`] = `


<  className="bDWFJH"
  spellCheck="false"
/>
`;

Note the missing element name in the snapshot. This appears to happen when the className matches the tag type. I tested with text inputs (classname "input") and textareas.

To confirm it was a conflict of class/tag, I tried changing the className to 'foo', which caused the tag name to appear correctly in the output.

To try to rule out styled-components or react itself (in case I was doing some sort of worst practice by doing this), I removed jest-styled-components from my tests. Without it, changing the className value had no noticeable impact on the output, so my best guess is that the issue is here.

Matcher for checking existence of property

Would you consider a pull request that either adds a matcher or modifies toHaveStyleRule to check the existence of a css property rather than a value? I'm writing a series of tests to ensure a collection of components adhere to some standards, so I want to write a test similar to:

expect(tree).not.toHaveStyleRule('margin');
expect(tree).not.toHaveStyleRule('padding');

to ensure components don't have any margin defined.

It could be added to toHaveStyleRule without a breaking change, but it might also make sense as just another matcher.

JavascriptHeap out of memory error

I've added the jest styled component 4.0.0-8 in a project an works with some test but if I run the full suite I receive this error:

<--- Last few GCs --->

[51821:0x105000000]     9070 ms: Mark-sweep 779.9 (790.3) -> 775.7 (790.3) MB, 179.7 / 0.0 ms  allocation failure GC in old space requested
[51821:0x105000000]     9516 ms: Mark-sweep 775.7 (790.3) -> 775.5 (783.3) MB, 446.3 / 0.0 ms  last resort 
[51821:0x105000000]     9767 ms: Mark-sweep 775.5 (783.3) -> 775.2 (783.3) MB, 250.6 / 0.0 ms  last resort 


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x1293e2e266a1 <JS Object>
    1: RegExpReplace [native regexp.js:~356] [pc=0x179e8c420ef7](this=0x28ffb9fd3b29 <JS RegExp>,z=0x12cd89302201 <Very long string[42284031]>,ak=0x28ffb9fd3b09 <String[3]: c21>)
    2: 0x2cfeccec9c11 <Symbol: Symbol.replace>(aka [Symbol.replace]) [native regexp.js:1] [pc=0x179e8c37d789](this=0x28ffb9fd3b29 <JS RegExp>,z=0x12cd89302201 <Very long string[42284031]>,ak=0x28ffb9fd3b09 <String[3]: ...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

I'll try to isolate the error and reproduce it in an open source environment.

toHaveStyleRule with enzyme

first of all: I really like the idea of testing styled-components and thanks for sharing this project!!

I did a very simple test project, to try it out and I would like to use it with enzyme, because I love their find-API and so on...

I did a very simple test as follow:

import React from 'react';
import styled from 'styled-components';
import { mount } from 'enzyme';
import renderer from 'react-test-renderer'
import toJson from 'enzyme-to-json';
import 'jest-styled-components';

const RedBox = styled.div`
    background-color: red;
`;

function MagicBox(props) {
    return <RedBox>
        <div className="here">An apple a day keeps the doctor away.</div>
    </RedBox>
}

test('renderer from react-test-renderer works', () => {
    const magicBox = renderer.create(<MagicBox/>);
    const magicBoxTree = magicBox.toJSON();
    expect(magicBoxTree).toHaveStyleRule('background-color', 'red');
});

test('enzyme does not work', () => {
    const magicBox = mount(<MagicBox/>);
    const magicBoxTree = toJson(magicBox);
    expect(magicBoxTree).toHaveStyleRule('background-color', 'red')
});

test('enzyme with selecting styled.div does work', () => {
    const magicBox = mount(<MagicBox/>);
    const magicBoxTree = toJson(magicBox.find('div').at(0));
    expect(magicBoxTree).toHaveStyleRule('background-color', 'red')
});

test('enzyme with selecting div within styled.div does not work', () => {
    const magicBox = mount(<MagicBox/>);
    const magicBoxTree = toJson(magicBox.find('div').at(1));
    expect(magicBoxTree).toHaveStyleRule('background-color', 'red')
});

The 2. and 4. tests are failing with Property not found: "background-color", which they shouldn't from my understanding. Did I miss something completly (like jest-styled-component needs a JSDOM for enzyme's mount or anything?)

For easy reconstruction I published the test project here.

Thanks again in advance!

Issue with CircleCI

Hello, I'm having trouble with the snapshot testing and I don't know what to do ๐Ÿ˜ญ.

Dependencies:

In my own PC (win10) it works everything OK. But when CircleCI executes the tests, it throws the following diff:

- .hvMUct > img {
-   filter: drop-shadow(-2px 2px 2px rgba(0, 0, 0, 0.5));
+ .lihsux > img {
+   filter: drop-shadow(-2px 2px 2px rgba(0,0,0,0.5));
}

Every ,{blank} space are stripped everywhere QQ

Thank you for your work :)

How does this behave in 2 SC projects using together

Just a question, not a bug @MicheleBertoli. I'm evaluating using SC and especially this jest plugin to make it work better since SC is changing the css classnames too many times (even sometimes when no css has changed).

Lets say I'm using a UI library (MyCustomBootstrapUI), which is built using styled-components.

I have my own app, called MySuperApp, which is also using styled-components, with jest-styled-components to have super nice snapshots.

MySuperApp is using MyCustomBootstrapUI v1. Then, MyCustomBootstrapUI gets updated to v1.1. One component changed to add a new css prop.

When updating MySuperApp to use the new UI v1.1, is it expected to have a snapshot difference/conflict because of the new css prop in the UI library?
From what I understand, there will be a difference, since jest-styled-component is outputing the css into the snapshots for all SC components. So, I wonder if it's expected, if we should have that or not. It could be nice in some ways I guess, to easily see in the project side what has changed, but it could also add a lot of noises too?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.