storybook/docs/snippets/react/nextjs-navigation-mock.ts-4-9.mdx
2024-04-30 22:21:31 -06:00

42 lines
1.1 KiB
Plaintext

```ts
// MyForm.stories.ts
import { expect, fireEvent, userEvent, within } from '@storybook/test';
import { Meta, StoryObj } from '@storybook/react';
// 👇 Must use this import path to have mocks typed correctly
import { redirect, getRouter } from '@storybook/nextjs/navigation.mock';
import MyForm from './my-form';
const meta = {
component: MyForm,
parameters: {
nextjs: {
// 👇 As in the Next.js application, next/navigation only works using App Router
appDirectory: true,
},
},
} satisfies Meta<typeof MyForm>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Unauthenticated: Story = {
async play() => {
// 👇 Assert that your component called redirect()
await expect(redirect).toHaveBeenCalledWith('/login', 'replace');
},
};
export const GoBack: Story = {
async play({ canvasElement }) {
const canvas = within(canvasElement);
const backBtn = await canvas.findByText('Go back');
await userEvent.click(backBtn);
// 👇 Assert that your component called back()
await expect(getRouter().back).toHaveBeenCalled();
},
};
```