Reputation: 31
I have an action that uses Promise.allSettled to return multiple stat objects from an API.
When I run the tests with mocking I get the error
Promise.allSettled is not a function
I have a get endpoint to returns different types of stats.
myapi.com/get_stats/:type
I have an action for this API as follows
const types = ['seo', 'referrers', 'clicks', 'posts', 'videos'];
const promises = [];
types.forEach(type =>
promises.push(
api().stats.getStats(type),
),
);
Promise.allSettled(promises).then(res => {
const { statData, statErrors } = mapData(res); // Data manipulation
dispatch({ type: FETCH_STATS_RESOLVED, payload: { statData, statErrors } });
});
My Test set up
jest.mock('api-file.js', () => ({
api: () => ({
stats: {
getStats: type => {
switch (type) {
case: 'seo':
return mockSeoStats;
}
}
}
})
}));
in beforeEach()
mockSeoStats.mockImplementation(() => Promise.resolve({ value: {data: myData} }));
I can see that the Action is receiving these mocked values, but Promise.allSettled is complaining
I assume it's having a hard time with the jest mock structure
So, how can i mock Promise.allSettled to just return what I expect it to, instead of looking at my mocked functions?
Upvotes: 3
Views: 8868
Reputation: 11
Try wrapping Promise.allSettled
in try-catch
block if you don't want to update node js.
Example:
try {
Promise.allSettled([
// your code
]).finally(() => {
// your code`enter code here`
});
} catch (e) {
console.log('promise.allSettled', e);
}
Upvotes: -3
Reputation: 492
A similar question was asked at Execute batch of promise with Promise.allSettled() Promise.allSettled is available from Node version 12.0 +
You can update node using Node's version manager
nvm ls
# Look for a 12.17.0 version (latest)
nvm install 12.17.0
# Automatically switches to new version
npm run test
# Should properly run your Promise.all
Hope that helped.
Upvotes: 5