aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-on-route-change/use-on-route-change.test.tsx
blob: afcad0a2410db84d242d1174f10bf8b9b1d5278e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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();
  });
});