【问题标题】:Unit testing of styled-components with SVG imports使用 SVG 导入对样式化组件进行单元测试
【发布时间】:2018-07-16 09:01:48
【问题描述】:

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

我在网络应用程序中看不到任何重大更改,但我的测试用例已损坏。

考虑以下愚蠢且无用的测试。

test('does something', () => {
  expect(true).toBe(true);
});

正如预期的那样,测试成功了。但是,一旦我尝试在测试文件中导入样式组件,它就会失败。

我添加了以下导入。

import {Container} from './styled';

Container styled-component 是这样定义的:

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]

现在,我不明白发生了什么。为什么我不能导入样式组件?

编辑

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

【问题讨论】:

    标签: javascript reactjs jestjs styled-components


    【解决方案1】:

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

    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 资产。

    为此,我们需要配置 jest。

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

    在 svgMock.js 中

    module.exports = '';
    

    在我现有的设置中,我有

    module.exports = {};
    

    虽然这适用于 styled-components-1.x,但它在 >=styled-components-2.x 上失败了。

    以下博客文章为我指明了答案:https://diessi.ca/blog/how-to-exclude-css-images-anything-from-unit-tests/

    【讨论】:

      猜你喜欢
      • 2019-03-26
      • 2020-03-07
      • 2020-09-26
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多