【发布时间】: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 失败的吗?代码/错误消息是什么?