Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking dynamic route params in Next 13 app dir

I'm using Jest and testing library to run unit tests on my NextJS app but struggling to figure out how to render a page on a dynamic path.

For my page/component:

export default async function MyPage({ params }: { params: { id: string }}) {
    return (<p>{params.id}</p>)
}

When trying to run a test:

import { render, screen } from '@testing-library/react';
import MyPage from './page'

it('renders', () => {
    render(<MyPage params={{ id: 'test' }} />)
    expect(screen.findByText('test')).toBeTruthy()
}

I get the following error:

TypeError: Cannot destructure property 'params' of 'undefined' as it is undefined.

How can I define the params object to render this component? I've tried passing it in as a normal prop in this example but I've also attempted to mock the router and force the params property in there with no luck. Has anyone had success mocking the params object that gets populated in dynamic routes under the app directory structure?

like image 313
Jason Gross Avatar asked Dec 06 '25 07:12

Jason Gross


1 Answers

Without RSC or app router features

it('should render', async () => {
  render(
    <Suspense>
      <Page params={{ username: 'DN' }} />
    </Suspense>
  );
});

With RSC or app router features

it('should render', async () => {
  render(await Page({params: {username: 'DN' }}))
});
like image 148
Darshan Naik Avatar answered Dec 08 '25 20:12

Darshan Naik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!