繁体   English   中英

测试组件DidUpdate酶reactjs

[英]testing componentDidUpdate enzyme reactjs

我正在尝试测试这个简单的 componentDidUpdate,但我似乎无法终生涵盖它。

这就是我测试它的方式。

  it('should run storeCardDesigns if conditions are met on componentDidUpdate', () => {
    const props = {
      isLoading: () => false,
      loadedWithErrors: () => false,
      storeCardDesigns: jest.fn(),
      availableCardDesigns: [],
    };

    const renderedModule = shallow(<GalleryModal {...props} />);
    renderedModule.setProps({ availableCardDesigns: [{ id: 'test1' }, { id: 'test2' }] });
    expect(renderedModule).toMatchSnapshot();

});

z

更好的方法是针对storeCardDesigns进行测试(这涵盖了if/else两种情况——否则,为了仅涵盖else情况,您可以简单地更新一个 prop 并期望 storeCardDesigns 没有被调用):

it("calls storeCardDesigns if the 'availableCardDesigns' prop changes", () => {
    const storeCardDesigns = jest.fn();
    const availableCardDesigns = [{ id: 'test1' }, { id: 'test2' }];

    const initialProps = {
      isLoading: false, // why is this a function? why not a simple boolean?
      loadedWithErrors: false, // why is this a function? why not a simple boolean?
      storeCardDesigns, // utilizes mock fn above
      availableCardDesigns: [], // initially empty
    };

    // shallow wrap component with initial props
    const wrapper = shallow(<GalleryModal {...initialProps} />);

    // update availableCardDesigns prop to trigger CDU lifecycle
    wrapper.setProps({ availableCardDesigns }); 

    expect(storeCardDesigns).toHaveBeenCalledWith(availableCardDesigns);

    // clear mock
    storeCardDesigns.mockClear();

    // update another prop update to trigger CDU
    wrapper.setProps({ isLoading: true });

    expect(storeCardDesigns).toHaveBeenCalledTimes(0);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM