Skip to content

Commit 8072b39

Browse files
authored
Merge pull request #125 from myty/feature/handle-undefined-window-v2
handle undefined window in network connection utilities
2 parents 5c37924 + 4bb154a commit 8072b39

2 files changed

Lines changed: 28 additions & 16 deletions

File tree

src/utilities/network-information-utils.test.ts

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,27 @@ import buildNetworkInformationUtils, {
33
NetworkInformationUtils,
44
} from "./network-information-utils";
55

6+
const buildMockWindow = (navigator?: Navigator) => {
7+
return { navigator } as Window & typeof globalThis;
8+
};
9+
10+
const buildMockNavigator = (
11+
connectionProperty?: string,
12+
onLine: boolean = false
13+
): Navigator => {
14+
const isOnline = onLine ?? navigator.onLine;
15+
16+
if (connectionProperty != null) {
17+
return {
18+
...navigator,
19+
onLine: isOnline,
20+
[connectionProperty]: {},
21+
};
22+
}
23+
24+
return { ...navigator, onLine: isOnline };
25+
};
26+
627
const setupSut = (options?: {
728
buildNavigator?: boolean;
829
buildWindow?: boolean;
@@ -16,22 +37,11 @@ const setupSut = (options?: {
1637
onLine = false,
1738
} = options ?? {};
1839

19-
const buildMockNavigator = (): Navigator => {
20-
const isOnline = onLine ?? navigator.onLine;
21-
22-
if (connectionProperty != null) {
23-
return {
24-
...navigator,
25-
onLine: isOnline,
26-
[connectionProperty]: {},
27-
};
28-
}
29-
30-
return { ...navigator, onLine: isOnline };
31-
};
40+
const navigator = buildNavigator
41+
? buildMockNavigator(connectionProperty, onLine)
42+
: undefined;
3243

33-
const navigator = buildNavigator ? buildMockNavigator() : undefined;
34-
const window = buildWindow ? ({ navigator } as Window) : undefined;
44+
const window = buildWindow ? buildMockWindow(navigator) : undefined;
3545

3646
return buildNetworkInformationUtils(window);
3747
};

src/utilities/network-information-utils.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ export default function buildNetworkInformationUtils(window?: Window) {
4747
// #region Exports
4848
// -----------------------------------------------------------------------------------------
4949

50-
export const NetworkInformationUtils = buildNetworkInformationUtils(window);
50+
export const NetworkInformationUtils = buildNetworkInformationUtils(
51+
typeof window !== "undefined" ? window : undefined
52+
);
5153

5254
// #endregion Exports

0 commit comments

Comments
 (0)