Search code examples
typescriptjestjsfetch

Simple fetch mock using Typescript and Jest


What would be my absolute easiest way of mocking fetch using Typescript?

I would just like to do something simple like below. But Typescript tells me that I'm not matching the definition for the full fetch object.

Type 'Mock<Promise<{ json: () => Promise<{ test: number; }>; }>, []>' is not assignable to type '(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>'.
   Type 'Promise<{ json: () => Promise<{ test: number; }>; }>' is not assignable to type 'Promise<Response>'.
     Type '{ json: () => Promise<{ test: number; }>; }' is missing the following properties from type 'Response': headers, ok, redirected, status, and 11 more.

What would be the simplest solution to get around this? Actually mock out the whole fetch object or other solution?

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ test: 100 }),
  }),
)

Solution

  • You can tell TypeScript that you're defining global.fetch as a Jest mock.

    global.fetch = jest.fn(() =>
      Promise.resolve({
        json: () => Promise.resolve({ test: 100 }),
      }),
    ) as jest.Mock;