diff --git a/src/__tests__/utils-node.test.ts b/src/__tests__/utils-node.test.ts new file mode 100644 index 0000000..1b3dc00 --- /dev/null +++ b/src/__tests__/utils-node.test.ts @@ -0,0 +1,11 @@ +/** + * @jest-environment node + */ + +import { isServer } from '../core/utils'; + +describe('utils-node-env', () => { + test('isServer should work', async () => { + expect(isServer).toBe(true); + }); +}); diff --git a/src/core/utils/index.ts b/src/core/utils/index.ts index 5c2bf14..5e0ea20 100644 --- a/src/core/utils/index.ts +++ b/src/core/utils/index.ts @@ -17,10 +17,12 @@ export const isFunction = (fn: unknown): fn is Function => export const isNil = (val: unknown) => val === null || val === undefined; +export const isServer = typeof window === 'undefined'; + export const isDocumentVisibility = () => - window?.document?.visibilityState === 'visible'; + !isServer && window?.document?.visibilityState === 'visible'; -export const isOnline = () => window?.navigator?.onLine ?? true; +export const isOnline = () => (!isServer && window?.navigator?.onLine) ?? true; export const unRefObject = (val: T) => { const obj = {}; diff --git a/src/core/utils/listener.ts b/src/core/utils/listener.ts index d9bd9f0..2cfea0b 100644 --- a/src/core/utils/listener.ts +++ b/src/core/utils/listener.ts @@ -1,4 +1,4 @@ -import { isDocumentVisibility } from './index'; +import { isDocumentVisibility, isServer } from './index'; type EventFunc = () => void; type ListenersSet = Set; @@ -40,7 +40,7 @@ const observer = (listeners: ListenersSet) => { }; /* istanbul ignore else */ -if (window?.addEventListener) { +if (!isServer && window?.addEventListener) { window.addEventListener( 'visibilitychange', () => {