Skip to content

Commit bd35d73

Browse files
Means88kamilogorek
authored andcommitted
fix: use a static object as fallback of the global object (#1901)
* fix: use a static object as fallback of the global object * test: add test for getGlobalObject
1 parent da7a115 commit bd35d73

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

packages/utils/src/misc.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,22 @@ export function isNodeEnv(): boolean {
2020
return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
2121
}
2222

23+
const fallbackGlobalObject = {};
24+
2325
/**
2426
* Safely get global scope object
2527
*
2628
* @returns Global scope object
2729
*/
2830
// tslint:disable:strict-type-predicates
2931
export function getGlobalObject(): Window | NodeJS.Global | {} {
30-
return isNodeEnv() ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {};
32+
return isNodeEnv()
33+
? global
34+
: typeof window !== 'undefined'
35+
? window
36+
: typeof self !== 'undefined'
37+
? self
38+
: fallbackGlobalObject;
3139
}
3240
// tslint:enable:strict-type-predicates
3341

packages/utils/test/misc.test.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { getEventDescription } from '../src/misc';
1+
import { getEventDescription, getGlobalObject } from '../src/misc';
22

33
describe('getEventDescription()', () => {
44
test('message event', () => {
@@ -108,3 +108,14 @@ describe('getEventDescription()', () => {
108108
).toEqual('<unknown>');
109109
});
110110
});
111+
112+
describe('getGlobalObject()', () => {
113+
test('should return the same object', () => {
114+
const backup = global.process;
115+
delete global.process;
116+
const first = getGlobalObject();
117+
const second = getGlobalObject();
118+
expect(first).toEqual(second);
119+
global.process = backup;
120+
});
121+
});

0 commit comments

Comments
 (0)