Storybook ❎ NextAuth: How to set mock auth session

lada496

Yuko

Posted on September 2, 2024

Storybook ❎ NextAuth: How to set mock auth session

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>
    }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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',
        },
      },
    }
Enter fullscreen mode Exit fullscreen mode

That’s it! Thank you for reading :)

The whole code is available here.
The oritinal ariticle is here

💖 💪 🙅 🚩
lada496
Yuko

Posted on September 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related