From 95a29578ec3e52d124ac6328694dfc028dcaba25 Mon Sep 17 00:00:00 2001 From: Marcos Passos Date: Fri, 4 Jun 2021 12:38:11 -0400 Subject: [PATCH] Fix Plug initialization on server-side --- src/hooks/useCroct.ssr.test.tsx | 18 ++++++++++++++++++ src/ssr-polyfills.ssr.test.ts | 8 ++++++++ src/ssr-polyfills.ts | 5 ++++- 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 src/hooks/useCroct.ssr.test.tsx diff --git a/src/hooks/useCroct.ssr.test.tsx b/src/hooks/useCroct.ssr.test.tsx new file mode 100644 index 00000000..33e8a76d --- /dev/null +++ b/src/hooks/useCroct.ssr.test.tsx @@ -0,0 +1,18 @@ +import {renderHook} from '@testing-library/react-hooks/server'; +import {ReactNode} from 'react'; +import {useCroct} from './useCroct'; +import {CroctProvider} from '../CroctProvider'; + +describe('useCroct', () => { + it('should not fail on server-side rendering', () => { + const {result} = renderHook(() => useCroct(), { + wrapper: ({children}: {children?: ReactNode}) => ( + + {children} + + ), + }); + + expect(result.error).toBeUndefined(); + }); +}); diff --git a/src/ssr-polyfills.ssr.test.ts b/src/ssr-polyfills.ssr.test.ts index 31315914..ac9de8fe 100644 --- a/src/ssr-polyfills.ssr.test.ts +++ b/src/ssr-polyfills.ssr.test.ts @@ -19,6 +19,14 @@ describe('Croct polyfill (SSR)', () => { expect(croct.unplug).not.toHaveBeenCalled(); }); + it('should not initialize', () => { + expect(croctPolyfill.initialized).toBe(false); + + croctPolyfill.plug({appId: '00000000-0000-0000-0000-000000000000'}); + + expect(croctPolyfill.initialized).toBe(false); + }); + it('should not allow accessing properties other than plug or unplug', () => { expect(() => croctPolyfill.user) .toThrow('Property croct.user is not supported on server-side (SSR).'); diff --git a/src/ssr-polyfills.ts b/src/ssr-polyfills.ts index dde808b4..527bd936 100644 --- a/src/ssr-polyfills.ts +++ b/src/ssr-polyfills.ts @@ -5,8 +5,11 @@ export function isSsr(): boolean { } export const croct: Plug = !isSsr() ? csrPlug : new Proxy(csrPlug, { - get(_, property) { + get(_, property: keyof Plug) { switch (property) { + case 'initialized': + return false; + case 'plug': return () => { // no-op