简体   繁体   English

使用SVG导入对样式组件进行单元测试

[英]Unit testing of styled-components with SVG imports

I am in the process of upgrading the dependencies of a React project. 我正在升级React项目的依赖项。 I upgraded styled-components from 1.4.4 to 2.5.0-1 . 我将样式组件从1.4.4升级到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. 我没想到任何重大变化,因为我读到样式组件v2是v1的替代品。

I don't see any breaking changes in the web app, but my test cases are broken. 我没有在Web应用程序中看到任何重大更改,但我的测试用例已被破坏。

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: 因此定义了Container样式组件:

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. 问题在于导入svg资产的样式组件。 See answer below. 见下面的答案。

After commenting out one styled component at a time, I figured out that the problem was with styled-components that use svg assets. 在一次评论出一个样式组件后,我发现问题出在使用svg资产的样式组件上。 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). 现在,我们的单元测试无法将SVG资产导入为React组件(通过Webpack处理)。 We therefore need to inform our unit tests to ignore SVG assets. 因此,我们需要通知我们的单元测试忽略SVG资产。

For that, we need to configure jest. 为此,我们需要配置jest。

"moduleNameMapper": {
      "\\.(svg)$": "<rootDir>/test/__mocks__/svgMock.js"
    }

And in svgMock.js 并在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. 虽然这与styled-components-1.x一起使用但却失败了> = 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//diessi.ca/blog/how-to-exclude-css-images-anything-from-unit-tests/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM