测试组件DidUpdate酶的反应js。

问题描述 投票:0回答:1

我正在尝试测试这个简单的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

javascript reactjs testing enzyme jest
1个回答
1
投票

一个更好的方法是测试 storeCardDesigns (这包括 if/else 否则,只需涵盖 else 的情况下,你可以简单地更新一个道具,并期望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);
});
© www.soinside.com 2019 - 2024. All rights reserved.