HomeToolsAbout

Promise

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); }); };

Test

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'); });
AboutContact