next-router-mock icon indicating copy to clipboard operation
next-router-mock copied to clipboard

`next/link` not working with `passHref`

Open brandonparis opened this issue 2 years ago • 1 comments

Hey there,

Spent a while trying many different things but ultimately I think there's something up with the behavior of next-router-mock when passHref is used with next/link. We use Stitches CSS to wrap the Link component.

The issue is the mockRouter just never updating.

Let me know if there's something you find here, I very well could be doing something wrong but I've exhausted all different things I could think to try.

const Breadcrumb = ({ history }: Props) => {
  const router = useRouter();
  return (
    <Navigation>
      <Arrow height={16} width={16} onClick={() => router.back()} name="ChevronLeft" />
      <List>
        {history.map((item) => {
          return (
            <Crumb key={item.id}>
              <Link passHref href={{ pathname: item.pathname, query: item.query }}> // next Link
                <CustomLink active={item.active}>{item.name}</CustomLink> // anchor tag
              </Link>
            </Crumb>
          );
        })}
      </List>
    </Navigation>
  );
};
jest.mock('next/router', () => jest.requireActual('next-router-mock'));
const history = [
    {
      pathname: '/admin/plans',
      query: null,
      name: 'Plans',
      id: 'plans',
      active: false,
    },
    {
      pathname: '/admin/plans',
      query: { planId: 1 },
      name: 'Plan 1',
      id: 'plan-1',
      active: true,
    },
  ];
test('clicking previous link should navigate back', () => {
    render(<Breadcrumb history={history} />, { wrapper: MemoryRouterProvider });
    const link = screen.getByRole('link', { name: 'Plans' });

    userEvent.click(link);

    expect(mockRouter).toMatchObject({
      asPath: '/admin/plans',
      pathname: '/admin/plans',
      query: {},
    });
  });

Screenshot 2023-08-10 at 7 58 30 AM

Next v12 next-router-mocker v0.9.8

brandonparis avatar Aug 10 '23 15:08 brandonparis

I don't see anything wrong with this code, but I think it would be nice to see the implementation of <CustomLink>.
I think the way that next/link works is that it'll pass the href to the child, but it also has extra functionality, so it passes things like onClick too.
If you're not passing onClick too, then clicking the link will just have the default Anchor tag behavior, and won't actually call router.push. So that's my guess.

scottrippey avatar Aug 15 '23 18:08 scottrippey