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 call 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");
});

it("should be undefined.", () => {
  windowSpy.mockImplementation(() => undefined);

  expect(window).toBeUndefined();
});

to create the windowSpy with jest.spyOn.

And then we call windowSpy.mockImplementation with a function that returns a mocked window object.

Then we call expect to check the value of the mocked window.location.origin property in the test.

Likewise, we call mockImplementation with a callback that returned undefined in the 2nd test.

Then window would be undefined in the 2nd test.

We call windowSpy.mockRestore after each test to restore it to the original value.

Conclusion

To mock the JavaScript window object using Jest, we can call 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. Required fields are marked *