如何通过Jest模拟Node.js中的fetch函数?
如何通过Jest模拟Node.js中的fetch函数 api.js如何通过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
'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。