Mock navigation in Storybook 7 with Next.js 13 App Router #25470
Unanswered
StephenSHorton
asked this question in
Help
Replies: 3 comments 5 replies
-
Hi, I'm facing similar situation (#26084). Have you found out any solution for this? |
Beta Was this translation helpful? Give feedback.
1 reply
-
Im using the app router and initially had the same Issue, but I managed to get it working. Heres what I did
and in my navigation components (I'm using a
now |
Beta Was this translation helpful? Give feedback.
2 replies
-
I was also struggling with the same issue, but it was resolved with Storybook 8.1. import type { Preview } from "@storybook/react";
import {
ReadonlyURLSearchParams,
getRouter,
usePathname,
useSearchParams,
} from "@storybook/nextjs/navigation.mock";
import { useMemo } from "react";
import mockRouter from "next-router-mock";
const preview: Preview = {
parameters: {
nextjs: {
appDirectory: true,
},
},
beforeEach: () => {
getRouter().push.mockImplementation(
(...args: Parameters<typeof mockRouter.push>) => mockRouter.push(...args)
);
getRouter().replace.mockImplementation(
(...args: Parameters<typeof mockRouter.replace>) =>
mockRouter.replace(...args)
);
usePathname.mockImplementation(() => mockRouter.pathname);
useSearchParams.mockImplementation(() => {
const searchParams = useMemo(
() =>
new ReadonlyURLSearchParams(
new URLSearchParams(mockRouter.query as Record<string, string>)
),
[mockRouter.query]
);
return searchParams;
});
},
};
export default preview; |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
How do I simulate navigation and capture the new pathname in a component?
I have been made aware of the zero-config nextjs/storybook integration. It appears the next/navigation is 'mocked' and I can manipulate it in my story like so
I have tried to use
usePathname
fromnext/navigation
But I've found out that due to navigation being mocked I can't access changes to the pathname through
usePathname
. Is there any way I can latch onto the changes in pathname and affect the state of my component to present in my Story?Additional information
Using Storybook version
^7.6.6
Here's my
.storybook > main.ts
Create a reproduction
No response
Beta Was this translation helpful? Give feedback.
All reactions