Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

jestjs

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.

like image 286
Youichi Okada Avatar asked Nov 26 '18 15:11

Youichi Okada


People also ask

How do you mock fetch in Jest react?

A correct and safe way to mock globals is to mock them before each test and restore after each test: beforeEach(() => { jest. spyOn(global, 'fetch'). mockResolvedValue({ json: jest.

Can you use fetch on Node?

With version 17.5, Node. js has made experimental support for the Fetch API available. Since then, we no longer need to install a third-party library to create server-side JavaScript code that utilizes the Fetch API.

What to use instead of fetch in node JS?

Axios: Axios is a Javascript library used to make HTTP requests from node. js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6.


2 Answers

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)
        });

    });
});
like image 100
Andreas Köberle Avatar answered Sep 22 '22 15:09

Andreas Köberle


import fetch, { Response } from 'node-fetch';

jest.mock('node-fetch');

describe('fetch-mock test', () => {
    const mockFetch = fetch as jest.MockedFunction<typeof fetch>;

    it('check fetch mock test', async () => {
      const json = jest.fn() as jest.MockedFunction<any>;
      json.mockResolvedValue({ status: 200}); //just sample expected json return value
      mockFetch.mockResolvedValue({ ok: true, json } as Response); //just sample expected fetch response
      await makeRequest();
      expect(json.mock.calls.length).toBe(1);
    })
})
like image 35
Kerisnarendra Avatar answered Sep 21 '22 15:09

Kerisnarendra