diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-11-15 17:09:13 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-11-15 17:26:17 +0100 |
| commit | 36baf3e5725aeae00d81d3a082b3c04074e09f8e (patch) | |
| tree | 34069dc40f7cd45707e8cea0a8993e94841af778 /src/utils/hooks/use-on-route-change/use-on-route-change.test.tsx | |
| parent | c826ad66df066b90b09009f2f4b83b56d018436e (diff) | |
refactor(hooks): replace useRouteChange with useOnRouteChange hook
* handle both event start and event complete
* clean the effect
* add tests
Diffstat (limited to 'src/utils/hooks/use-on-route-change/use-on-route-change.test.tsx')
| -rw-r--r-- | src/utils/hooks/use-on-route-change/use-on-route-change.test.tsx | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/utils/hooks/use-on-route-change/use-on-route-change.test.tsx b/src/utils/hooks/use-on-route-change/use-on-route-change.test.tsx new file mode 100644 index 0000000..afcad0a --- /dev/null +++ b/src/utils/hooks/use-on-route-change/use-on-route-change.test.tsx @@ -0,0 +1,69 @@ +import { describe, it } from '@jest/globals'; +import { render, screen as rtlScreen } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; +import Link from 'next/link'; +import nextRouterMock from 'next-router-mock'; +import { MemoryRouterProvider } from 'next-router-mock/MemoryRouterProvider'; +import { + type OnRouteChangeHandler, + useOnRouteChange, + type OnRouteChangeStep, +} from './use-on-route-change'; + +type TestComponentProps = { + callback: OnRouteChangeHandler; + href: string; + step?: OnRouteChangeStep; +}; + +const TestComponent = ({ callback, href, step }: TestComponentProps) => { + useOnRouteChange(callback, step); + + return ( + <MemoryRouterProvider> + <Link href={href}>New page</Link> + </MemoryRouterProvider> + ); +}; + +describe('useOnRouteChange', () => { + it('trigger a callback when the route change event starts', async () => { + const cb = jest.fn(); + const user = userEvent.setup(); + const newPage = '/new-page'; + + nextRouterMock.push('/initial-page'); + + render(<TestComponent callback={cb} href={newPage} />); + + expect(cb).not.toHaveBeenCalled(); + + await user.click(rtlScreen.getByRole('link')); + + expect(nextRouterMock).toMatchObject({ + asPath: newPage, + pathname: newPage, + }); + expect(cb).toHaveBeenCalled(); + }); + + it('can trigger a callback when the route change event is complete', async () => { + const cb = jest.fn(); + const user = userEvent.setup(); + const newPage = '/new-page'; + + nextRouterMock.push('/initial-page'); + + render(<TestComponent callback={cb} href={newPage} step="end" />); + + expect(cb).not.toHaveBeenCalled(); + + await user.click(rtlScreen.getByRole('link')); + + expect(nextRouterMock).toMatchObject({ + asPath: newPage, + pathname: newPage, + }); + expect(cb).toHaveBeenCalled(); + }); +}); |
