【问题标题】:testing componentDidUpdate enzyme reactjs测试组件DidUpdate酶reactjs
【发布时间】:2020-04-22 18:46:49
【问题描述】:

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

});

【问题讨论】:

    标签: javascript reactjs testing jestjs enzyme


    【解决方案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);
    });
    

    【讨论】:

    • 非常感谢您添加 cmets 来解释思考过程。那真的很有帮助。现在的问题是这个 `expect(storeCardDesigns).toHaveBeenCalledWith(availableCardDesigns); ` 被调用了 0 次。
    • 尝试几个调试步骤:1.) 检查拼写错误 2.) 组件CDU 中的控制台日志availableCardDesigns 以确保它正在被更改。如果它没有被更改并且拼写正确,那么您可能需要使用mount 而不是shallow
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2021-03-14
    • 2016-08-20
    • 1970-01-01
    • 2017-06-03
    • 2017-08-16
    • 2018-01-17
    • 1970-01-01
    相关资源
    最近更新 更多