.resolves
and .rejects
By using .resolves
matcher, Jest will wait for that Promise to resolve.
// resolves test('testing Promise return expected resolved value', async () => { await expect( async () => await service.fetchData()).resolves.toBe('value'); }); // rejects test('testing Promise rejects to throw an expected error', async () => { await expect( async () => await service.fetchData()).rejects.toThrow(new NotFoundError().message); });
Implementation
// myModule.js // Function that returns a Promise export const fetchData = () => { return new Promise((resolve, reject) => { // Some asynchronous operation setTimeout(() => { resolve('Mocked Data'); }, 1000); }); };
Testing for resolved result:
import { fetchData } from './myModule'; jest.mock('./myModule'); // Automatically mocks the entire module test('should mock the return value of fetchData', async () => { // Set the mocked return value fetchData.mockResolvedValue('Mocked Data'); // Your test code that uses fetchData const result = await fetchData(); // Assertions expect(result).toBe('Mocked Data'); });
Alternatively, testing for Promise value:
(fetchData as jest.Mock).mockReturnValue(Promise.resolve()) (fetchData as jest.Mock).mockReturnValue(Promise.reject())