How to test a Next.js component with dynamic route using Jest

  • last month
In Next.js Dynamic Routes is a powerful feature that allows you to create routes based on dynamic segments in the URL, making your application more flexible and scalable.

This video shows how to use Jest to test a component for a Dynamic Route where is extracted the dynamic route from url and used as prop.

#nextjs14 #nextjstutorial #nextjs #next #jest
Transcript
00:00In my Next.js app, I'm using a dynamic root for this file.
00:13It's dynamic because it receives a dynamic root as parameter in URL.
00:25The component for the dynamic root receives an object
00:40containing the dynamic root parameter extracted from the URL.
00:49And the extracted parameter is being passed as code to this child component.
01:05In this child component, I have a form where user can enter a new password
01:13and the code will be used as user identifier.
01:20I need to test this component using Jest.
01:29In my test, I should provide a dynamic root parameter that matches this exact structure.
01:43My dynamic root parameter will be fake, but I need to add it to respect this format.
02:01In my component, I have a child component where the URL dynamic root extracted from the URL is passed as a prop called code.
02:27I won't test the child component in my test file.
02:35Instead, I have created a mock for it using a fake component
02:46that receives a code prop identical to the original component.
03:05Now, let's run a test.
03:16And the test is being passed as expected.

Recommended