Как установить тест для нескольких выборок с Promise.all, используя Jest

Я использую шутку для своих тестов. Я использую реаги и редуксы, и у меня есть это действие:

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

Я искал в документации шутка, как установить тест для этого действия, но я не смог найти способ. Я попробовал себя примерно так:

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
});

Неудачно. Так как мне действовать?

1 ответ

Решение

Использовать Promise.all Вы могли бы сделать следующее

test('Testing Stuff', async (done) => {

  const expectedActions = [{ foo: {...}, bar: {...} }, { foo: {...}, bar: {...} }];

  // we pass the index to this function 
  const asyncCall = async (index) => {
    // check some stuff
    expect(somestuff).toBe(someOtherStuff);
    // await the actual stuff
    const response = await doStuff( expectedActions[index] );
    // check the result of our stuff
    expect(response).toBe(awesome);
    return response;
  };

  // we put all the asyncCalls we want into Promise.all 
  const responses = await Promise.all([
    asyncCall(0),
    asyncCall(1),
    ...,
    asyncCall(n),
  ]);

  // this is redundant in this case, but wth
  expect(responses).toEqual(awesome);

  done();

});

Вы можете указать Jest дождаться разрешения обещания, вернув обещание в обратном вызове. См. Этот раздел здесь для получения дополнительной информации.

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());
});
Другие вопросы по тегам