我如何通过Jest模拟Node.js中的fetch函数?

hwamh0ep  于 2022-12-26  发布在  Node.js
关注(0)|答案(3)|浏览(118)

我如何通过Jest模拟Node.js中的fetch函数?
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)
        });

    });
});

我尝试使用jest-fetch-mock、nock和jest.mock,但是失败了。
谢谢。

m1m5dgzv

m1m5dgzv1#

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

ddrv8njm2#

我发现在Jest中模拟ECMAScript模块最简单的方法是使用jest.unstable_mockModule
示例:

jest.unstable_mockModule("node-fetch", () => ({
  default: (url) => {
    if (url.includes("/groups/")) {
      return {
        ok: true,
        json: () => ({
          id: dummyGuid,
          name: "dummyStringForName",
          embedUrl: "https://example.com",
          datasetId: dummyGuid,
        }),
      }
    }
    if (url.endsWith("/GenerateToken")) {
      return {
        ok: true,
        json: () => ({
          token: "dummyStringForToken",
        }),
      }
    }
  },
}))
jucafojl

jucafojl3#

您可以使用jest.mock模拟node-fetch,然后在测试集中模拟实际响应

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

    });
});

相关问题