问题
I am in the process of upgrading the dependencies of a React project. I upgraded styled-components from 1.4.4
to 2.5.0-1
. I didn't expect any breaking changes since I read that styled-components v2 is a drop-in replacement for v1.
I don't see any breaking changes in the web app, but my test cases are broken.
Consider the following, dumb and useless test.
test('does something', () => {
expect(true).toBe(true);
});
As expected, the test works. However, as soon as I even try to import a styled-component in the test file, it fails.
I added the following import.
import {Container} from './styled';
The Container styled-component is defined thus:
export const Container = styled.div`
width: 80%;
display: flex;
flex-direction: column;
transition: opacity 0.25s ease-in-out;
`;
I get the following error:
Cannot create styled-component for component: [object Object]
Right now, I fail to understand what's going on. Why can't I import a styled-component?
EDIT
The problem was with styled-components that import svg assets. See answer below.
回答1:
After commenting out one styled component at a time, I figured out that the problem was with styled-components that use svg assets. Consider the following styled-component
import Edit from 'assets/edit-icon.svg';
export const EditIcon = styled(Edit)`
transition: opacity 0.25s ease-in-out;
position: absolute;
opacity: 0;
z-index: 2;
&:hover {
transform: scale(1.05);
}
&:active {
transform: scale(0.93);
}
`;
Now, our unit tests can't import SVG assets as React Components (that is handled via Webpack). We therefore need to inform our unit tests to ignore SVG assets.
For that, we need to configure jest.
"moduleNameMapper": {
"\\.(svg)$": "<rootDir>/test/__mocks__/svgMock.js"
}
And in svgMock.js
module.exports = '';
In my existing setup, I had
module.exports = {};
And while this worked with styled-components-1.x it failed with >=styled-components-2.x.
The following blog post pointed me towards an answer: https://diessi.ca/blog/how-to-exclude-css-images-anything-from-unit-tests/
来源:https://stackoverflow.com/questions/48640647/unit-testing-of-styled-components-with-svg-imports