酶不会 'render, mount, or shallow' 组件,因为依赖项未定义

Enzyme wont 'render, mount, or shallow' a component because a dependency is undefined

我想弄清楚为什么我的测试不会 运行。我有一个 React 功能组件,其中包含一个样式化组件,它使用自定义方法生成一个媒体查询,该媒体查询被导入到一个 css 帮助程序文件中。我收到 TypeError: Cannot read property 'medium' of undefined。这是我的代码。

css/index.js

export const media = (function(){

  const sizes = {
    large: 996,
    medium: 767,
    small: 656,
  };

  return Object.keys(sizes).reduce((acc, label) => {
    acc[label] = (...args) => css`
      @media (min-width: ${sizes[label] / 16}em) {
        ${css(...args)}
      }
    `;
    return acc;
  }, {});

})();

我的组件

import { media } from 'css';

const MyComponent = ({ icon, title, description }) => (
  <MyComponentContainer>
    ...
  </MyComponentContainer>
);

export default MyComponent;

const MyComponentContainer = styled.article`
  max-width: 300px;
  width: 100%;
  border: 1px solid #000;
  ${media.medium`
    padding: 0 25px;
  `}
  ${media.large`
    max-width: 350px;
  `}
`;

我的测试文件

import React from 'react';
import { shallow } from 'enzyme';

import MyComponent from 'components/MyComponent';

describe('<MyComponent />', () => {

  it('should match the snapshot', () => {

    const snap = shallow(<MyComponent />);
    expect(snap).toMatchSnapshot();

  });

});

我是 React 测试的新手,并不真正了解如何模拟该功能或告诉 jest 忽略它。

我正在使用带有所需酶适配器和 jest-styled-components 测试插件的 React 16+。

以防其他人遇到这个问题,我找到了答案,它解释了很多关于测试的本质。

测试时,您只想一次测试一个组件或动作的功能(单元测试)。通过尝试测试引入另一个依赖项的组件,我实际上是在不知不觉中同时测试两件事。

MyComponent 组件需要与 media 标记的模板方法分开测试。

MyComponent 中,我不关心从 media 标记的模板方法返回了什么。我只关心调用了什么方法和调用的参数。

我可以为 media 方法设置另一个单独的测试以确保这些方法按预期运行并单独测试它们。

所以在jest中你可以模拟模块导入。

在我的测试文件中

import React from 'react';
import { shallow } from 'enzyme';

import MyComponent from 'components';

jest.mock('css', () => ({
   media: {
      small: jest.fn(),
      medium: jest.fn(),
      large: jest.fn(),
   },
})

describe('<MyComponent />, () => {
    it('should match snapshot', () => {
        const snap = shallow(<MyComponent />);
        expect(snap).toMatchSnapshot();
    });
});