1

How can I mock window to be undefined?

This will help me out testing some scenarios of SSR.

Is the

Object.defineProperty()

a solution, not quite sure how I could mock it



Thank you for the help in advance.

1 Answer 1

1

Yes, Object.defineProperty() is a solution.

E.g.

index.ts:

function main() {
  return window;
}

export default main;

index.test.ts:

import main from '.';

describe('60152407', () => {
  it('should return window', () => {
    expect(main()).toBeDefined();
  });
  it('should mock window to be undefined', () => {
    Object.defineProperty(global, 'window', { value: undefined });
    expect(main()).toBeUndefined();
  });
});

unit test results with coverage report:

 PASS  stackoverflow/60152407/index.test.ts
  60152407
    ✓ should return window (2ms)
    ✓ should mock window to be undefined (1ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.792s, estimated 5s

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'enzyme',
  setupFilesAfterEnv: ['jest-enzyme', './jest.setup.js'],
  testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
  verbose: true,
};

Source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60152407

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

1 Comment

Any idea how to restore window after setting it? Any tests that comes after fails because window is not defined.

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.