带有SVG导入的样式化组件的单元测试 [英] Unit testing of styled-components with SVG imports

查看:82
本文介绍了带有SVG导入的样式化组件的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在升级React项目的依赖项.我将样式组件从1.4.4升级到了2.5.0-1.我没想到会有任何重大变化,因为我读到样式化组件v2是v1的直接替代品.

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.

我看不到Web应用程序中的任何重大更改,但是我的测试用例已损坏.

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.

我添加了以下导入.

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;
`;

我收到以下错误:

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?

编辑

问题在于导入svg资产的样式化组件.请参阅下面的答案.

The problem was with styled-components that import svg assets. See answer below.

推荐答案

一次注释掉一个样式化组件后,我发现问题出在使用svg资产的样式化组件.考虑以下样式化组件

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);
  }
`;

现在,我们的单元测试无法将SVG资产作为React组件(通过Webpack处理)导入.因此,我们需要通知我们的单元测试以忽略SVG资产.

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"
    }

在svgMock.js中

And in svgMock.js

module.exports = '';

在我现有的设置中,我拥有

In my existing setup, I had

module.exports = {};

尽管这与styled-components-1.x一起使用,但失败了,但> = styled-components-2.x.

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/

这篇关于带有SVG导入的样式化组件的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆