DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Updated on

Jest Mock fetch

// Assuming you have a function that returns a Promise
function fetchData() {
  return fetch('https://example.com/data.json').then(response => response.json());
}

// Create a mock function for fetch
const mockFetch = jest.fn();

// Mock the resolved value for the first call to fetch
mockFetch.mockResolvedValueOnce({ data: 'mocked data' });

// Replace the original fetch function with the mock
global.fetch = mockFetch;

// Now, when you call fetchData, it will use the mocked value for the first call
fetchData().then(data => {
  console.log(data); // { data: 'mocked data' }
});

// You can also assert how many times the mock function was called
expect(mockFetch).toHaveBeenCalledTimes(1);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)