fetch-mock不会嘲笑我的fetch [英] fetch-mock does not mock my fetch
问题描述
下面是代码段:
var fetch = require("node-fetch");
var fetchMock = require("fetch-mock");
function setupMockBlockChainExplorer() {
fetchMock.mock("https://cardanoexplorer.com/api/addresses/summary/DdzFFzCqrhsmagp4fDZpcY9UaBJk4Z8GaDfxqMCSwxPs3PnVoXmJWUZcgAxw3diCHVYauontEfk7YGeAu2LvAwq3aG2XQ8Mtsz7Vc8LA", {
"status" : 200,
"body" : "override"
});
}
async function makeRequest(url, method = "get", body = null, headers = null) {
const res = await fetch(url, {
method: method,
headers: headers,
body: body,
});
return res.json()
};
setupMockBlockChainExplorer();
var req = makeRequest("https://cardanoexplorer.com/api/addresses/summary/DdzFFzCqrhsmagp4fDZpcY9UaBJk4Z8GaDfxqMCSwxPs3PnVoXmJWUZcgAxw3diCHVYauontEfk7YGeAu2LvAwq3aG2XQ8Mtsz7Vc8LA");
// I would expect it to print "override" but it prints the http response from the real request instead
req.then(console.log)
因此,正如您在上面的代码中看到的那样,我正在尝试覆盖HTTP请求,但是我仍然使用fetch来访问真实的URL.我已经阅读了fetch-mock文档( http://www.wheresrhys.co. uk/fetch-mock/installation.html ),我还尝试过这样设置配置:
So I'm trying to override a HTTP request as you can see in the code above, but I'm still hitting the real URL with fetch. I have read the fetch-mock docs (http://www.wheresrhys.co.uk/fetch-mock/installation.html) and I also tried setting the config like this:
fetchMock.config = Object.assign(fetchMock.config, {
"fetch": fetch
});
但是没有运气.我在做什么错了?
but with no luck. What am I doing wrong?
推荐答案
我认为问题在于您没有使用fetch
的全局"版本.
I think the issue is that you are not using the 'global' version of fetch
.
尝试使用isomorphic-fetch
代替node-fetch
.
此处.
请注意这句话:
使用import 'isomorphic-fetch'
,而不是import fetch from 'isomorphic-fetch'
Use import 'isomorphic-fetch'
, not import fetch from 'isomorphic-fetch'
这篇关于fetch-mock不会嘲笑我的fetch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!