Yasser Shaikh
Yasser Shaikh

Reputation: 47804

How to test window objects using jest tests

I am trying to test a class which returns values depending on values present in window object.

window.test = 123;

I want to mock the window object's test property to 123 value to be able to test correctly.

I tried Object.defineProperty, using global instead, but nothing seems to work. Seems like a trivial question but not able to find the answer on google or elsewhere. Please advice.

Upvotes: 5

Views: 6456

Answers (1)

Estus Flask
Estus Flask

Reputation: 223318

In case window exists (i.e. Jest runs with JSDOM, which is done by default) it should be:

beforeEach(() => {
  window.test = 123;
});

afterEach(() => {
  delete window.test;
});

In case it doesn't exist, it's:

beforeEach(() => {
  global.window = { test: 123 };
});

afterEach(() => {
  delete global.window;
});

Depending on whether window is used elsewhere, it may be beneficial to back it up to temporary variable in beforeEach and restore in afterEach.

Upvotes: 4

Related Questions