useRouter is hook in Next.js that provides access to the router object, enabling developers to navigate between pages, access route parameters, and control various aspects of the routing in a Next.js application.
This video shows how to mock the useRouter for tests using Jest.
This video shows how to mock the useRouter for tests using Jest.
Category
🦄
CreativityTranscript
00:00I'm using the Next.js useRouter hook for redirects in my component and it works as expected.
00:21Now, I want to write a test for this component and the first test case is used to find the
01:10This error is generated because the useRouter hook is not available during the tests.
01:21To solve this problem, I will open my Jest setup file which is provided in the configuration file of Jest.
01:51And here I will create a mock for Next.navigation.useRouter hook.
02:08Now, let's run again the test and now the test is passed as expected.
02:38Now, let's run again the test and now the test is passed as expected.