styled-components / jest-styled-components

🔧 💅 Jest utilities for Styled Components
MIT License
1.59k stars 145 forks source link

jest-styled-components only works for the first snapshot in the test #317

Open absassi opened 4 years ago

absassi commented 4 years ago

When there are multiple snapshots in the same test, jest-styled-components only works for the first snapshot in the test.

Please see the following minimal example:

TestJestStyledComponents.jsx

import React from 'react';
import styled from 'styled-components';

const Bold = styled.span`
  font-weight: bold;
`;

export const TestJestStyledComponents = () => <Bold>Test</Bold>;

TestJestStyledComponents.test.jsx

import React from 'react';
import { render } from '@testing-library/react';
import 'jest-styled-components';

import { TestJestStyledComponents } from './TestJestStyledComponents';

it('works with two snapshots', () => {
  const { container } = render(<TestJestStyledComponents />);
  expect(container.firstChild).toMatchSnapshot();
  expect(container.firstChild).toMatchSnapshot();
});

__snapshots__/TestJestStyledComponents.test.jsx.snap

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

exports[`works with two snapshots 1`] = `
.c0 {
  font-weight: bold;
}

<span
  class="c0"
>
  Test
</span>
`;

exports[`works with two snapshots 2`] = `
<span
  class="sc-AxjAm gfJUZX"
>
  Test
</span>
`;
marcosvega91 commented 4 years ago

I have the same issue 😢

alex-at-cascade commented 3 years ago

Also seeing this. Is any workaround known?

CrawX commented 3 years ago

I can confirm this issue. The second (and later) snapshots look like jest-styled-components is not enabled at all. However, toHaveStyleRule seems to operate on the correct data, ie. the checks succeed & fail as expected. The serialized snapshot however does not reflect the style and does not contain any css at all (like outlined by @absassi).

9still commented 3 years ago

Having the same problem. Is there a way to get #319 merged? It's a pretty annoying issue.

marcosvega91 commented 3 years ago

I have opened a PR to fix it but is still there unfortunately :(

9still commented 3 years ago

Was able to implement the following ~workaround~ hack inspired by @marcosvega91's fix that appears to get around the issue without needing to fork:

import 'jest-styled-components';
import { styleSheetSerializer } from 'jest-styled-components/serializer';

const JEST_STYLED_COMPONENTS_KEY = '__jest-styled-components__';
const unmarkNode = (val) => {
  if (val && val[JEST_STYLED_COMPONENTS_KEY]) {
    delete val[JEST_STYLED_COMPONENTS_KEY];
    if (val.children) {
      [...val.children].forEach(unmarkNode);
    }
  }
};

// override the default styleSheetSerializer
const patchedStyleSheetSerializer = {
  test: styleSheetSerializer.test,
  print(val, print) {
    const result = styleSheetSerializer.print(val, print);
    unmarkNode(val);
    return result;
  }
};
expect.addSnapshotSerializer(patchedStyleSheetSerializer);