如何模拟未定义的窗口?
这将帮助我测试一些SSR场景。
是
Object.defineProperty()
一个解决方案,不太确定我该如何模拟它
谢谢您的提前帮助。
答案 0 :(得分:1)
是的,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