Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch-mock does not mock my fetch

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?

like image 486
Rafael K. Avatar asked Feb 28 '18 17:02

Rafael K.


1 Answers

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'

like image 99
alayor Avatar answered Nov 16 '22 23:11

alayor