【问题标题】:How can I mock fetch function in Node.js by Jest?如何通过 Jest 在 Node.js 中模拟 fetch 函数?
【发布时间】:2019-04-28 06:45:25
【问题描述】:

如何通过 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 但失败了。

谢谢。

【问题讨论】:

  • 你能说明它是如何用 nock 失败的吗?代码/错误消息是什么?

标签: node.js jestjs


【解决方案1】:
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);
    })
})

【讨论】:

    【解决方案2】:

    您可以使用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)
            });
    
        });
    });
    

    【讨论】:

    • 不知道为什么你会关心模拟它并在测试类中导入它......为什么不模拟它以便测试用于导入的目标代码获取,测试代码需要嘲笑那个。
    • fetch 在要测试的代码中返回undefined
    • 对我来说,fetch 是未定义的,我不能在它上面调用 mockImplementation。
    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2021-02-27
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多