Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a test for multiple fetches with Promise.all using jest

I'm using jest for my tests. I'm using react and redux and I have this action:

function getData(id, notify) {
 return (dispatch, ...) => {
   dispatch(anotherFunction());
   Promise.all(['resource1', 'resource2', 'resource3'])
   .then(([response1,response2,response3]) => {
        // ... handle responses
    })
   .catch(error => { dispatch(handleError(error)); }
 };
}

I've been looking for into the jest documentation how to set a test for this action, but I was unable to find a way. I tried myself something like this:

it('test description', (done) => {
  const expectedActions = [{type: {...}, payload: {...}},{type: {...}, payload: {...}},...];
  fetchMock.get('resource1', ...);
  fetchMock.get('resource2', ...);
  fetchMock.get('resource3', ...);
  // ... then the rest of the test calls
});

Unsuccessfully. So how should I proceed?

like image 893
assembler Avatar asked Jun 30 '17 13:06

assembler


People also ask

How do I resolve a promise in Jest?

Return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will fail.

How do you test a promise resolve?

Create a file named teams. js, import the API using require and create the function getTeamByPlayer it will return a promise, using setTimeout simulate the async process. Our promise return the resolve if the team with the player is found or the reject with an error if not found. Export the function to be used.

Do Jest tests run in parallel?

Each time a test run completes, the global environment is automatically reset for the next. Since tests are standalone and their execution order doesn't matter, Jest runs tests in parallel. This means that even if you have hundreds of unit tests you can run them frequently without the fear of having to wait.

Which statement must be used to set fake timers before all the tests in a Jest JavaScript file?

Enable Fake Timers​useFakeTimers() . This is replacing the original implementation of setTimeout() and other timer functions. Timers can be restored to their normal behavior with jest.


1 Answers

You can tell Jest to wait for the promise to resolve by returning the promise in the callback. See this section here for more info.

it('should fetch some food', () => {
  const fetchItem1 = () => fetchData1().then(data => {
    expect(data).toBe('peanut butter');
  })
  const fetchItem2 = () => fetchData2().then(data => {
    expect(data).toBe('boiled egg');
  })
  const fetchItem3 = () => fetchData3().then(data => {
    expect(data).toBe('fried salad');
  })

  return Promise.all([fetchItem1(), fetchItem2(), fetchItem3()])
    .then(() => runOtherTests());
});
like image 176
NearHuscarl Avatar answered Nov 16 '22 00:11

NearHuscarl