Reputation: 104
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.
Upvotes: 1
Views: 2803
Reputation: 102327
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
Upvotes: 1