Skip to content

How to mock useRouter from next/navigation? #48937

Discussion options

You must be logged in to vote

I had the same issue and finally I solved with implementing the following provider mock:

// app-router-context-provider-mock.tsx

import {
  AppRouterContext,
  AppRouterInstance,
} from 'next/dist/shared/lib/app-router-context';
import React from 'react';

export type AppRouterContextProviderMockProps = {
  router: Partial<AppRouterInstance>;
  children: React.ReactNode;
};

export const AppRouterContextProviderMock = ({
  router,
  children,
}: AppRouterContextProviderMockProps): React.ReactNode => {
  const mockedRouter: AppRouterInstance = {
    back: jest.fn(),
    forward: jest.fn(),
    push: jest.fn(),
    replace: jest.fn(),
    refresh: jest.fn(),
    prefetch: jest.fn(),
    ...r…

Replies: 8 comments 19 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
15 replies
@seenivasanb
Comment options

@brilliantmakanju
Comment options

@lawrence-cruz
Comment options

@pkrakesh
Comment options

@yoshiomiyamae
Comment options

Answer selected by lawrence-cruz
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
4 replies
@supertgo
Comment options

@martin-opensky
Comment options

@geraldofori
Comment options

@yguenduez
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment