Skip to content

Commit

Permalink
Fix Plug initialization on server-side
Browse files Browse the repository at this point in the history
  • Loading branch information
marcospassos committed Jun 4, 2021
1 parent 2643cf0 commit 95a2957
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
18 changes: 18 additions & 0 deletions src/hooks/useCroct.ssr.test.tsx
Original file line number Diff line number Diff line change
@@ -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}) => (
<CroctProvider appId="00000000-0000-0000-0000-000000000000">
{children}
</CroctProvider>
),
});

expect(result.error).toBeUndefined();
});
});
8 changes: 8 additions & 0 deletions src/ssr-polyfills.ssr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).');
Expand Down
5 changes: 4 additions & 1 deletion src/ssr-polyfills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 95a2957

Please sign in to comment.