Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 577
Murakami Avatar asked Aug 09 '18 14:08

Murakami


1 Answers

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).

like image 99
Brian Adams Avatar answered Oct 08 '22 03:10

Brian Adams