Да, Object.defineProperty()
- решение.
Например,
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();
});
});
результаты модульного теста с отчетом о покрытии:
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,
};
Исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60152407