close

How can I mock the JavaScript window object using Jest?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How can I mock the JavaScript window object using Jest? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How can I mock the JavaScript window object using Jest?

  1. How can I mock the JavaScript window object using Jest?

    can I mock the JavaScript window object using Jest I'm directly assigning jest.fn() to window.open.
    window.open = jest.fn() // ...code expect(window.open).toHaveBeenCalledTimes(1) expect(window.open).toHaveBeenCalledWith('/new-tab','__blank')

  2. How can I mock the JavaScript window object using Jest?

    can I mock the JavaScript window object using Jest I'm directly assigning jest.fn() to window.open.
    window.open = jest.fn() // ...code expect(window.open).toHaveBeenCalledTimes(1) expect(window.open).toHaveBeenCalledWith('/new-tab','__blank')

Method 1

The following method worked for me. This approach allowed me to test some code that should work both in the browser and in Node.js, as it allowed me to set window to undefined.

This was with Jest 24.8 (I believe):

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();
});

Method 2

I’m directly assigning jest.fn() to window.open.

window.open = jest.fn()
// ...code
expect(window.open).toHaveBeenCalledTimes(1)
expect(window.open).toHaveBeenCalledWith('/new-tab','__blank')

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment