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),我也尝试过这样设置配置:

fetchMock.config = Object.assign(fetchMock.config, {
    "fetch": fetch
});

但运气不好。我做错了什么?

我认为问题在于您没有使用 fetch 的 'global' 版本。

尝试使用 isomorphic-fetch 而不是 node-fetch

你可以看到更多的解释here

注意这句话:

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