How to test/mock navigation using next/link? (Next.js 14)
Unanswered
Common carp posted this in #help-forum
Common carpOP
I currently have this component and I wanted to ensure that it should always go to the '/' route everytime. However, I noticed there have been some issues with mocking Next's Link component.
<Link data-testid='lounge-logo-link' className='inline-block' href='/'>
<Image className='h-8 w-32' src={Logo} alt='Lounge logo' />
</Link>
3 Replies
@Common carp I currently have this component and I wanted to ensure that it should always go to the '/' route everytime. However, I noticed there have been some issues with mocking Next's Link component.
<Link data-testid='lounge-logo-link' className='inline-block' href='/'>
<Image className='h-8 w-32' src={Logo} alt='Lounge logo' />
</Link>
Masai Lion
You should try something like this:
'use client';
import Link from 'next/link';
import Image from 'next/image';
import Logo from '@/public/logo.png';
const component = () => {
return (
<Link href="/" data-testid="lounge-logo-link">
<Image src={Logo} alt="Lounge logo" className="h-8 w-32" />
</Link>
);
};
export default component;
Common carpOP
Hello @Masai Lion, thank you for your response! However, I wanted to have the Jest code instead.
@Common carp Hello <@1107387213559369832>, thank you for your response! However, I wanted to have the Jest code instead.
Masai Lion
import { render, screen } from '@testing-library/react';
import LoungeLogo from './LoungeLogo';
import '@testing-library/jest-dom';
jest.mock('next/link', () => {
return ({ children, href }) => {
return <a href={href}>{children}</a>;
};
});
test('LoungeLogo should always navigate to "/"', () => {
render(<LoungeLogo />);
const linkElement = screen.getByTestId('lounge-logo-link');
// Check if the link points to the homepage ('/')
expect(linkElement).toHaveAttribute('href', '/');
});
This is the only solution I find for your problem.