5

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.