jest-styled-components
jest-styled-components copied to clipboard
jest-styled-components only works for the first snapshot in the test
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>
`;
I have the same issue 😢
Also seeing this. Is any workaround known?
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).
Having the same problem. Is there a way to get #319 merged? It's a pretty annoying issue.
I have opened a PR to fix it but is still there unfortunately :(
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);