Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过Jest模拟Node.js中的fetch函数?_Node.js_Jestjs - Fatal编程技术网

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

如何通过Jest模拟Node.js中的fetch函数?,node.js,jestjs,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.export

如何通过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)
        });

    });
});
我试图使用,nock和jest.mock,但失败了


谢谢。

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

    });
});

你能展示一下nock是如何失败的吗?代码/错误消息是什么?不知道为什么您会关心模拟它并将其导入测试类。。。为什么不模拟它,以便测试的目标代码导入fetch,测试代码需要模拟它。fetch在要测试的代码中返回
未定义的
。对于我来说,fetch也是未定义的,我无法对其调用mockImplementation。