Categories
JavaScript Answers

How to mock the JavaScript window object using Jest?

Spread the love

Sometimes, we want to mock the JavaScript window object using Jest.

In this article, we’ll look at how to mock the JavaScript window object using Jest.

How to mock the JavaScript window object using Jest?

To mock the JavaScript window object using Jest, we can use the jest.spyOn method.

For instance, we write

let windowSpy;

beforeEach(() => {
  windowSpy = jest.spyOn(window, "window", "get");
});

afterEach(() => {
  windowSpy.mockRestore();
});

it('should return https://example.com', () => {
  windowSpy.mockImplementation(() => ({
    location: {
      origin: "https://example.com"
    }
  }));

  expect(window.location.origin).toEqual("https://example.com");
});

to call jest.spyOn to mock the get global function in the beforeEach callback.

In the afterEach callback, we call windowSpy.mockRestore to restore window to its original state.

And then we call windowSpy.mockImplementation to mock it window.get with a function that returns location.origin.

And then we check that window.location.origin is "https://example.com".

This test should pass because of the mock.

Conclusion

To mock the JavaScript window object using Jest, we can use the jest.spyOn method.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.