'Waiting for React component state to update before testing with Jest

I have a component with a handleAdd function. This function calls a library, which in turn calls axios and returns a promise. Once that's resolved, the handleAdd() method updates component state which in turns renders child(ren).

In other words, it checks with the server first to make sure the item is added before displaying it locally.

When testing with Jest, i have to await sleep for a few msec before the expect runs otherwise the shallow render isn't updated yet, even though I mock/overwrite the api call. There's some delay between the promise resolving, rerender and expect(). Here's what that kind of looks like:

it('adds a thing', async () => {
    ThingManager.default.addPlan = () => {
      const response = new Promise((resolve, reject) => { resolve() })
      return response;
    }

    const wrapper = shallow(<Home />)
    wrapper.find('button').simulate('click')
    const input = wrapper.find('#plan-title')
    input.simulate('change', { target: { value: 'TEST ITEM' } })

    await sleep(500) // without it, <Thing /> isn't rendered yet.

    expect(wrapper.find('Thing').length).toBe(1)
  });

What's the proper way of doing this?



Solution 1:[1]

Just wanted to throw it out there that I use simple setTimeout with the combination of jest's done().

EDIT

it('sample test case', (done) => {
        // initialize your component

        setTimeout(function () {
            // expect something that's available after the timeout
            done();
        }, 500);
    });

Solution 2:[2]

You can use act from test-utils. That is what the React docs recommend, but I have had more success with waitFor from testing-library.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 JulienD