【问题标题】:Enzyme wont 'render, mount, or shallow' a component because a dependency is undefined酶不会“渲染、挂载或浅化”组件,因为未定义依赖项
【发布时间】:2018-10-28 06:52:13
【问题描述】:

我想弄清楚为什么我的测试无法运行。我有一个 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();

  });

});

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

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

【问题讨论】:

    标签: javascript reactjs sinon enzyme styled-components


    【解决方案1】:

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

    在测试时,您只想一次测试一个组件或操作的功能(单元测试)。通过尝试测试一个引入另一个依赖项的组件,我实际上是在尝试同时测试两件事而没有意识到这一点。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2017-02-13
      • 2020-04-26
      • 2019-07-02
      • 2018-07-16
      • 1970-01-01
      相关资源
      最近更新 更多