Reputation: 188
How to mock the Link component from "next/link" with jest in Next JS and check the redirect path after a click on a link element?
Here an example component with a test:
import Link from "next/link";
export default function Nav() {
return (
<div>
<Link href="/login">
<span>Click here</span>
</Link>
</div>
)
}
describe("Nav", () => {
it("redirects correctly", async () => {
render(<Nav />)
fireEvent.click(screen.getByText("Click here"));
// check if redirect to href prop works as expected
});
});
Upvotes: 5
Views: 7083
Reputation: 438
You may wrap your test with RouterContext provider and pass the mock router as a value
import createMockRouter from 'src/test-utils/createMockRouter';
import { RouterContext } from 'next/dist/shared/lib/router-context';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
describe("Nav", () => {
let router = createMockRouter({});
it("redirects correctly", async () => {
render(
<RouterContext.Provider value={router}>
<Nav />
</RouterContext.Provider>)
waitFor(() => {
fireEvent.click(screen.getByText("Click here"));
expect(router.push).toHaveBeenCalledWith('/login');
});
});
});
And create a createMockRouter utility in your utils like this.
import { NextRouter } from 'next/router';
const createMockRouter = (router: Partial<NextRouter>): NextRouter => {
return {
basePath: '',
pathname: '/',
route: '/',
query: {},
asPath: '/',
back: jest.fn(),
beforePopState: jest.fn(),
prefetch: jest.fn(),
push: jest.fn(),
reload: jest.fn(),
replace: jest.fn(),
events: {
on: jest.fn(),
off: jest.fn(),
emit: jest.fn(),
},
isFallback: false,
isLocaleDomain: false,
isReady: true,
defaultLocale: 'en',
domainLocales: [],
isPreview: false,
...router,
};
};
export default createMockRouter;
Upvotes: 2