0

I'm trying to test this simple componentDidUpdate and I can not seem to get it covered for the life of me.

this how I'm testing it.

  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

1 Answer 1

1

A better approach would be to test against storeCardDesigns (this covers both if/else cases -- otherwise, to cover just the else case, you can simply update a prop and expect storeCardDesigns to not have been called):

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much for adding the comments to explain the thought process. That was really helpful. The issue now is that this ` expect(storeCardDesigns).toHaveBeenCalledWith(availableCardDesigns); ` is being called 0 times.
Several debugging steps to try: 1.) Check for spelling errors 2.) console log availableCardDesigns within the component's CDU to make sure it's being changed. If it's not being changed and the spelling is correct, then you may need to use mount instead of shallow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.