← Back to blog

How to mock global objects in jest

Sometimes we need to mock some global objects in our unit tests, and this article explains different ways to do it in jest.

Initial data

Let's assume that we have defined one global object in window, and also should mock fetch. It will look like:

window
  mySiteGlobal: {
    apiBaseUrl: "https://some-site-base-path.dot.com"
  }
  fetch: fn

And also have a js files with following content. I simplified logic inside files, but examples are based on real ones.

// user-helper.js

export const getUserProfileUrl = userId => {
  return `${window.mySiteGlobal.apiBaseUrl}/user?id=${userId}`;
};
// api-base-helper.js

export const get = path => {
  return fetch(window.mySiteGlobal.apiBaseUrl + url);
};

Writing unit tests

No we will try to write unit tests.