DEV Community

Chris Armstrong
Chris Armstrong

Posted on • Updated on • Originally published at

Testing node-fetch with jest in TypeScript

(This was originally posted on my development blog at, so check it out for more JavaScript and AWS related content!)

Because I haven't seen it anywhere else, and because it was a bit tricky to set up, here is an example of testing some code that uses the node-fetch library with TypeScript.

First install fetch-mock-jest, fetch-mock and its types package @types/fetch-mock.

Then, set up your test like follows:

import type { FetchMockStatic } from 'fetch-mock';
import fetch from 'node-fetch';

// We need this import to get the extra jest assertions

import 'fetch-mock-jest';

// Mock 'node-fetch' with 'fetch-mock-jest'. Note that using
// require here is important, because jest automatically 
// hoists `jest.mock()` calls to the top of the file (before 
// imports), so if we were to refer to an imported module, we 
// would get a `ReferenceError`

  () => require('fetch-mock-jest').sandbox(),

// Cast node-fetch as fetchMock so we can access the 
// `.mock*()` methods

const fetchMock = (fetch as unknown) as FetchMockStatic;

describe('code that uses fetch', () => {
  beforeEach(() => fetchMock.reset());

  it('should fetch a simple URL correctly', async () => {
    fetchMock.get('', { value: 1234 });
    await fetch('');
      url: ''

  it('should fetch with complex assertions', async () => {
      { status: 'ok' },

    const result = await fetch(
        method: 'post',
        body: JSON.stringify({
          type: 'create',
          details: {
            username: 'chris',
            passwordToken: 'abcde12345',
        headers: { 'content-type', 'application/json' },

    // Check we called the right URL, method and 
    // part of the body
        matchPartialBody: true,
        method: 'post',
        body: { type: 'create' },
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

imamdev_ profile image
Imamuzzaki Abu Salam

It suppousedly didn't work for a fetch inside a function. I need it.

amrahmddev profile image
Amr Ahmed

after hours of searching.. you saved my day, thank you.