Sometimes, we want to test promises in Jest.
In this article, we’ll look at how to test promises in Jest.
How to test promises in Jest?
To test promises in Jest, we can use the resolves.toEqual
and rejects.toEqual
methods.
For instance, we write
describe('Fetching', () => {
const filters = {
startDate: '2015-09-01'
};
const api = new TestApi();
it('should reject if no startdate is given', () => {
expect.assertions(1);
return expect(MyService.fetch()).rejects.toEqual({
error: 'Your code message',
});
});
it('should return expected data', () => {
expect.assertions(1);
return expect(MyService.fetch(filters, null, api)).resolves.toEqual(extectedObjectFromApi);
});
});
to call resolves.toEqual
to check the resolve value of the promise returned by MyService.fetch
method.
And we call rejects.toEqual
to test the rejection message of the promise returned by MyService.fetch()
.
Conclusion
To test promises in Jest, we can use the resolves.toEqual
and rejects.toEqual
methods.