This is my memo when I write stories that change depending on session states.
· 1. Create a mock provider
· 2. Add the provider to decorators at preview.tsx
· 3. Modify parameters in stories
∘ A. Set a default state
∘ B. Set a custom state
1. Create a mock provider
// ./storybook/mock-session-provider.tsx
import React from 'react'
import { SessionProvider } from 'next-auth/react'
export const MockSessionProvider = ({ session, children }) => {
return <SessionProvider session={session}>{children}</SessionProvider>
}
2. Add the provider to decorators at preview.tsx
import React from 'react'
import '../src/styles/globals.css'
import type { Preview } from '@storybook/react'
import { MockSessionProvider } from './mock-session-provider'
import '../src/styles/globals.css'
const preview: Preview = {
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
nextjs: {
appDirectory: true,
},
},
// Here!
decorators: [
(Story, { parameters }) => {
const { session } = parameters
return (
<MockSessionProvider session={session}>
<Story />
</MockSessionProvider>
)
},
],
}
export default preview
3. Modify parameters in stories
A. Set a default state
You can set session parameters in each component’s meta object to apply all stories for the component.
const meta = {
title: 'Components/InfoWindowCard',
component: InfoWindowCard,
parameters: {
session: {
status: 'authenticated',
},
},
} satisfies Meta<typeof InfoWindowCard>
B. Set a custom state
You can also set a custom state individually.
export const Logout: Story = {
args: {
...BASE_PROPS,
isMap: false,
},
parameters: {
session: {
status: 'unknown',
},
},
}
That’s it! Thank you for reading :)
The whole code is available here.
The oritinal ariticle is here
Top comments (0)