fetch-mock 不会模拟我的 fetch [英] fetch-mock does not mock my fetch

查看:35
本文介绍了fetch-mock 不会模拟我的 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.

Trying using isomorphic-fetch instead of node-fetch.

您可以在这里查看更多说明.

You can see more explanation here.

注意这句话:

使用 import 'isomorphic-fetch',而不是 import fetch from 'isomorphic-fetch'

Use import 'isomorphic-fetch', not import fetch from 'isomorphic-fetch'

这篇关于fetch-mock 不会模拟我的 fetch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆