Waiting for React component state to update before testing with Jest
Asked Answered
L

3

11

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?

Lapstrake answered 9/8, 2020 at 12:18 Comment(1)
The question is very specific to the lib you're using that seems to be Enzyme. Consider specifying this.Dextrorotation
A
4

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);
    });
Antediluvian answered 9/8, 2020 at 15:38 Comment(4)
newbie here. Can you please share an example?Registration
@NandanPhadke I've added an editAntediluvian
Waiting some arbitrary amount of time for some non deterministic event to happen is usually a bad solution.Lauralee
Going with @Lauralee here and I am a little worried that this is marked as the accepted answerAttrahent
G
8

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.

Gerous answered 9/8, 2020 at 13:3 Comment(0)
A
4

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);
    });
Antediluvian answered 9/8, 2020 at 15:38 Comment(4)
newbie here. Can you please share an example?Registration
@NandanPhadke I've added an editAntediluvian
Waiting some arbitrary amount of time for some non deterministic event to happen is usually a bad solution.Lauralee
Going with @Lauralee here and I am a little worried that this is marked as the accepted answerAttrahent
L
0

I'm not an enzyme user, but I do use jest. Here is how I do this with @testing-library/react. The recommendation is that you don't look at the state directly, but at the markup resulting from the state being set.

const view = render(<Thing />);
const input = await screen.findByTestId('input-test-id');
fireEvent.change(input, {
  target: {value: 'new value'},
});
// This element is then displayed as a result of the state getting set
// resulting from the change event. screen.findByTestId (or any screen.find*) waits for 
// the element to appear timing out if it does not.
expect(await screen.findByTestId('logo-image-test-id')).toBeDefined();
Lauralee answered 22/9, 2023 at 23:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.