fetch-mock does not mock my fetch

Rafael K. picture Rafael K. · Feb 28, 2018 · Viewed 8.3k times · Source

here is the code snippet:

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)

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?

Answer

alayor picture alayor · Feb 28, 2018

I think the issue is that you are not using the 'global' version of fetch.

Trying using isomorphic-fetch instead of node-fetch.

You can see more explanation here.

Note this sentence:

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