Skip to content

Commit

Permalink
feat: tests for context access wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick VanCise authored and Nick VanCise committed Jan 5, 2024
1 parent 330c25e commit 1e68cc3
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
64 changes: 64 additions & 0 deletions gbajs3/src/hooks/context.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import {
useAuthContext,
useEmulatorContext,
useLayoutContext,
useModalContext
} from './context.tsx';
import { AuthContext } from '../context/auth/auth.tsx';
import { EmulatorContext } from '../context/emulator/emulator.tsx';
import { LayoutContext } from '../context/layout/layout.tsx';
import { ModalContext } from '../context/modal/modal.tsx';

import type * as authContextExports from '../context/auth/auth.tsx';

describe('useContext hooks', () => {
beforeEach(() => {
vi.resetModules();
});

const contextHooks = [
[useAuthContext, AuthContext.displayName],
[useEmulatorContext, EmulatorContext.displayName],
[useLayoutContext, LayoutContext.displayName],
[useModalContext, ModalContext.displayName]
] as const;

it.each(contextHooks)(
'throws error when used outside of the proper provider',
(contextHook, contextName) => {
// silence console errors as they are expected
vi.spyOn(console, 'error').mockImplementation(() => {});

expect(() => {
renderHook(() => contextHook());
}).toThrow(
`${contextName} must be loaded under the matching ${contextName}.Provider`
);
}
);

it('throws error with default message if no context display name', async () => {
// silence console errors as they are expected
vi.spyOn(console, 'error').mockImplementation(() => {});

vi.doMock('../context/auth/auth.tsx', async () => {
const { AuthContext: original, ...rest } = await vi.importActual<
typeof authContextExports
>('../context/auth/auth.tsx');

return {
...rest,
AuthContext: { ...original, displayName: undefined }
};
});
// we must reimport the component under test
const { useAuthContext } = await import('./context.tsx');

expect(() => {
renderHook(() => useAuthContext());
}).toThrow(`This context must be loaded under the matching Provider`);
});
});
2 changes: 1 addition & 1 deletion gbajs3/src/hooks/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const useLoadContext = <T,>(context: Context<T>) => {
if (!loadedContext)
throw new Error(
`${displayName ?? 'This context'} must be loaded under the matching ${
displayName ? `${displayName}.Provider` : 'provider'
displayName ? `${displayName}.Provider` : 'Provider'
}`
);

Expand Down

0 comments on commit 1e68cc3

Please sign in to comment.