Skip to content Skip to sidebar Skip to footer

Unit Testing Of Styled-components With Svg Imports

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 sty

Solution 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

importEditfrom'assets/edit-icon.svg';

exportconstEditIcon = 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/

Post a Comment for "Unit Testing Of Styled-components With Svg Imports"