fetch-mock does not mock my fetch
Asked Answered
P

1

14

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?

Psychotomimetic answered 28/2, 2018 at 17:3 Comment(0)
E
11

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'

Erdah answered 28/2, 2018 at 17:30 Comment(7)
yes, the problem was that "var fetch = require("node-fetch")" at the beginning of the snippet. It should have been just "require("node-fetch")"Psychotomimetic
and yes, I had to replace node-fetch with isomorphic fetch as you suggestedPsychotomimetic
I had to use import 'isomorphic-fetch' in the unit test and in the file that I was testing in order for it to work.Corrosion
the issue isn't with node-fetch - both libraries will work if the import/require statement is correctTann
the link in your answer is badHendershot
@lfender6445 It's fixed now. Thanks!Erdah
This is what happens when you implement the examples in the "quick start" without reading the rest of the docs.Turbid

© 2022 - 2024 — McMap. All rights reserved.