Categories
JavaScript Answers

How to mock globals in Jest and JavaScript?

Spread the love

Sometimes, we want to mock globals in Jest and JavaScript.

In this article, we’ll look at how to mock globals in Jest and JavaScript.

How to mock globals in Jest and JavaScript?

To mock globals in Jest and JavaScript, we can use the spyOn and mockImplementation methods.

For instance, in the beforeAll callback, we write

jest.spyOn(window, "navigator", "get").mockImplementation(() => {
  //...
});

to call spyOn to create a mock for the window.navigator.get method.

And then we call mockImplemenetation on the returned mocked object with a callback with the mocked implementation of window.navigator.get.

Then in the afterAll callback, we write

jest.restoreAllMocks();

to clear all the mocks.

Conclusion

To mock globals in Jest and JavaScript, we can use the spyOn and mockImplementation methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *