简体   繁体   中英

setTimeout in Jest/Enzyme Tests

Here's the chunk of my code:

   it("saving flow (entering into edit mode and saving) works correctly", (done) => {

const wrapper = mount(
  <Root>
    <DictionaryRooms/>
  </Root>
);

moxios.wait(() => {
  wrapper.update();


  wrapper.find('.btn-dark').at(1).simulate('click');

  setTimeout(() => {
    expect(wrapper.find('.editField span').at(0).text().trim()).toEqual(jsonDataRooms.data[0].name);
  }, 1000);

  done();
  wrapper.unmount();
})

  });

So as you can see I'm tying to simulate clicking on the button, which in my app cause downloading some new data from backend server. These data would be visible just after my backend data will come in and then it will be displayed. So again after my request is done I'm trying to check if the new data is what I'm expecting to have. Obviously, after clicking it needs time to be downloaded and it will be displayed after a while. That's why I need something like setTimeout. But that won't work. Don't know why...

Thanks for any suggestions.

The call to setTimeout() will queue a callback but the test keeps executing synchronously and calls done() and wrapper.unmount() before the callback has a chance to execute.

Call those within the setTimeout() callback:

setTimeout(() => {
  expect(wrapper.find('.editField span').at(0).text().trim()).toEqual(jsonDataRooms.data[0].name);
  wrapper.unmount();
  done();
}, 1000);

There might be other issues with the test (the code being tested isn't provided) but making that change will get you closer. You also probably don't need to wait a second, using a timeout of 0 is likely enough (there is probably a queued callback that just needs to execute before the expect ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM