How to overwrite fetch using Javascript?

Viewed 537

I want to test my React app and mock the backend calls. I decided to replace fetch by a Jest function that returns a constant.

The problem is that I can't overwrite the default fetch value. I googled a bunch and found global.fetch = ... to overwrite fetch but I'm not sure what global means. I tried just writing var fetch = ... in my test file but did not work although the component is within the scope of component.

I'm happy to hear alternative solutions for mocking fetch.

// Does not work
import component that fetches
test(...){
  var fetch = ...
  <component that fetches/>
}
// Works
import component that fetches
test(...){
  global.fetch = ...
  <component that fetches/>
}
1 Answers

It's expected that the first option doesn't work because fetch variable is local to a function where it was defined. although the component is within the scope of component statement doesn't make much sense, that a component is nested (or more specifically, React element, because <Comp/> translates to React.createElement(Comp)) doesn't mean it can access anything from that scope except variables that were specifically passed as props.

This works like:

function foo() {
  var fetch = 'local';
  var someGlobal = 'local';
  console.log(fetch); // a global shadowed by a local
  console.log(someGlobal); // a global shadowed by a local
  bar(someGlobal);
}

function bar(someGlobal) {
  console.log(fetch); // a global
  console.log(someGlobal); // a global shadowed by a local
}

Since real requests aren't supposed to be performed in tests, it's acceptable to mock fetch by assigning it to a global like global.fetch = ..., but for other globals this would it impossible to restore original implementation. Generally, Jest spies should never be set by assignment. Instead, spyOn is used:

beforeEach(() => {
  jest.spyOn(global, 'fetch').mockImplementation(...)
});

This allows the framework to restore original implementation if needed, this spy works correctly with both resetAllMocks and restoreAllMocks.

Related