【问题标题】:How to snapshot test a component with nested component?如何使用嵌套组件对组件进行快照测试?
【发布时间】:2019-09-17 10:15:27
【问题描述】:

我正在测试一个带有嵌套组件的组件,其中使用了 redux。我正在对组件使用浅层测试。 这是我的测试:

describe("Header", () =>
  void it("renders correctly", () => {
    const renderer = new ShallowRenderer()
    const tree = renderer.render(<Header />)
    expect(tree).toMatchSnapshot();
  })

快照输出为:

exports[`Header renders correctly 1`] = `
<mockConstructor
  render={[Function]}
/>
`;

这是正确的吗?快照不应该显示我的组件吗?

【问题讨论】:

    标签: javascript reactjs redux jackson jestjs


    【解决方案1】:

    我按照你说的修改了我的代码,你的 sn-p 的快照输出是:

    exports[`Header renders correctly 1`] = `ShallowWrapper {}`;
    

    查找有关此输出的信息,我发现 Jest/Enzyme ShallowWrapper is empty when creating Snapshot 基本上我必须使用酶转json,所以我将代码更改为:

    import { shallow } from 'enzyme';
    import toJson from 'enzyme-to-json';
    ...
    
    describe("Header", () =>
      void it("renders correctly", () => {
        const tree = shallow(<Header />)
        expect(toJson(tree)).toMatchSnapshot()
      })
    )
    

    enzyme-to-json 的 github 站点中,有一个示例显示为我的测试

    import React, {Component} from 'react';
    import {shallow} from 'enzyme';
    import toJson from 'enzyme-to-json';
    
    it('renders correctly', () => {
      const wrapper = shallow(
        <MyComponent className="my-component">
          <strong>Hello World!</strong>
        </MyComponent>
      );
    
      expect(toJson(wrapper)).toMatchSnapshot();
    });
    

    但快照是:

    exports[`Header renders correctly 1`] = `
    <mockConstructor
      render={[Function]}
    />
    `;
    

    【讨论】:

      【解决方案2】:

      尝试使用 enzyme 包中的 shallow

      import { shallow } from 'enzyme';
      import Header from './Header';
      
      describe('Header', () => {
        it('should render', () => {
          const wrapper = shallow(<Header />);
          expect(wrapper).toMatchSnapshot();
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-03
        • 2019-07-26
        • 2017-05-21
        • 2019-04-26
        • 2019-07-13
        • 2017-05-25
        • 1970-01-01
        相关资源
        最近更新 更多