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

You*_*ada 9 node.js jestjs

如何通过 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;
Run Code Online (Sandbox Code Playgroud)

测试.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)
        });

    });
});
Run Code Online (Sandbox Code Playgroud)

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

谢谢。

小智 13

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);
    })
})
Run Code Online (Sandbox Code Playgroud)


And*_*rle 7

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

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

    });
});
Run Code Online (Sandbox Code Playgroud)

  • fetch 在要测试的代码中返回“undefined”。 (2认同)
  • 对我来说, fetch 是未定义的,我无法对其调用 mockImplementation 。 (2认同)