node.jsjestjs

How can I mock fetch function in Node.js by Jest?


How can I mock fetch function in Node.js by Jest?

api.js

'use strict'
var fetch = require('node-fetch');

const makeRequest = async () => {
    const res = await fetch("http://httpbin.org/get");
    const resJson = await res.json();
    return resJson;
};

module.exports = makeRequest;

test.js

describe('fetch-mock test', () => {
    it('check fetch mock test', async () => {

        var makeRequest = require('../mock/makeRequest');

        // I want to mock here


         global.fetch = jest.fn().mockImplementationOnce(() => {
           return new Promise((resolve, reject) => {
            resolve({
                ok: true,
                status,
                json: () => {
                    return returnBody ? returnBody : {};
                },
               });
          });
        });

        makeRequest().then(function (data) {
            console.log('got data', data);
        }).catch((e) => {
            console.log(e.message)
        });

    });
});

I tried to use jest-fetch-mock, nock and jest.mock but failed.

Thanks.


Solution

  • You can mock node-fetch using jest.mock. Then in your test set the actual mock response

    import fetch from 'node-fetch'
    jest.mock('node-fetch', ()=>jest.fn())
    
    describe('fetch-mock test', () => {
        it('check fetch mock test', async () => {
    
            var makeRequest = require('../mock/makeRequest');
    
    
             const response = Promise.resolve({
                    ok: true,
                    status,
                    json: () => {
                        return returnBody ? returnBody : {};
                    },
                   })
            fetch.mockImplementation(()=> response)
            await response
            makeRequest().then(function (data) {
                console.log('got data', data);
            }).catch((e) => {
                console.log(e.message)
            });
    
        });
    });