HomeAbout

Promise

Async Jest

.resolves and .rejects

By using .resolves matcher, Jest will wait for that Promise to resolve.

  • If the Promise is rejected, it'll automatically fail.
// 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); });

Mocking Promise

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())
AboutContact