How to set a test for multiple fetches with Promise.all using jest
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());
});
To use Promise.all
you could do the following
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();
});