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'
};
@gloorx Just FYI, I set this up on my project today with no problem. I am using create-react-app, so my config is different than yours, but I can say for sure that the blanket statement of "Doesn't work" !== true
Thanks @gloorx for opening the issue, and thanks @duro for confirming that the library actually works. The tests are still green on this repo :)
I tried to run your code @gloorx and I can confirm it works as expected, the problem is more about what shallow rendering actually does.
In fact, shallow rendering renders the components one level deep which means that your Wrapper is rendered as a styled.div.
If you just dive into it a level more:
const wrapper = shallow(<Button />);
expect(wrapper.dive()).toMatchSnapshot();
You'll see a div with the class applied to it:
- Snapshot
+ Received
-<styled.div>
+.c0 button {
+ color: red;
+}
+
+<div
+ className="c0"
+>
<button>
hello
</button>
-</styled.div>
+</div>
I hope this helps.
Most helpful comment
Thanks @gloorx for opening the issue, and thanks @duro for confirming that the library actually works. The tests are still green on this repo :)
I tried to run your code @gloorx and I can confirm it works as expected, the problem is more about what shallow rendering actually does.
In fact, shallow rendering renders the components one level deep which means that your
Wrapperis rendered as astyled.div.If you just dive into it a level more:
You'll see a
divwith the class applied to it:I hope this helps.