Mocking Fetch With Vitest

Here’s some starter code to mock fetch calls in Vitest:

import { vi } from 'vitest';

export function mockFetch(resolver) {
  vi.stubGlobal(
    'fetch',
    vi.fn().mockImplementation((url) => {
      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve(resolver(url)),
        status: 200,
        statusText: 'OK',
        clone: function () {
          return { ...this };
        },
      });
    }),
  );
}

vi.stubGlobal is great for mocking other globals too, like location and history:

vi.stubGlobal('location', {
  href: 'https://example.com',
  assign: vi.fn(),
});

vi.stubGlobal('history', {
  replaceState: vi.fn(),
});

Mock responsibly, friends.

References