Back to Storybook

Nextjs Cache Mock

docs/_snippets/nextjs-cache-mock.md

10.3.63.0 KB
Original Source
js
import { expect } from 'storybook/test';

// Replace your-framework with nextjs or nextjs-vite
import { revalidatePath } from '@storybook/your-framework/cache';

import MyForm from './my-form';

export default {
  component: MyForm,
};

export const Submitted = {
  async play({ canvas, userEvent }) {
    const submitButton = canvas.getByRole('button', { name: /submit/i });
    await userEvent.click(saveButton);
    // ๐Ÿ‘‡ Use any mock assertions on the function
    await expect(revalidatePath).toHaveBeenCalledWith('/');
  },
};
ts
// Replace your-framework with nextjs or nextjs-vite
import type { Meta, StoryObj } from '@storybook/your-framework';

import { expect } from 'storybook/test';

// ๐Ÿ‘‡ Must include the `.mock` portion of filename to have mocks typed correctly
import { revalidatePath } from '@storybook/your-framework/cache.mock';

import MyForm from './my-form';

const meta = {
  component: MyForm,
} satisfies Meta<typeof MyForm>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Submitted: Story = {
  async play({ canvas, userEvent }) {
    const submitButton = canvas.getByRole('button', { name: /submit/i });
    await userEvent.click(saveButton);
    // ๐Ÿ‘‡ Use any mock assertions on the function
    await expect(revalidatePath).toHaveBeenCalledWith('/');
  },
};
ts
import { expect } from 'storybook/test';

/*
 * Replace your-framework with nextjs or nextjs-vite
 * ๐Ÿ‘‡ Must include the `.mock` portion of filename to have mocks typed correctly
 */
import { revalidatePath } from '@storybook/your-framework/cache.mock';

import preview from '../.storybook/preview';

import MyForm from './my-form';

const meta = preview.meta({
  component: MyForm,
});

export const Submitted = meta.story({
  async play({ canvas, userEvent }) {
    const submitButton = canvas.getByRole('button', { name: /submit/i });
    await userEvent.click(saveButton);
    // ๐Ÿ‘‡ Use any mock assertions on the function
    await expect(revalidatePath).toHaveBeenCalledWith('/');
  },
});
<!-- JS snippets still needed while providing both CSF 3 & Next -->
js
import { expect } from 'storybook/test';

// Replace your-framework with nextjs or nextjs-vite
import { revalidatePath } from '@storybook/your-framework/cache';

import preview from '../.storybook/preview';

import MyForm from './my-form';

const meta = preview.meta({
  component: MyForm,
});

export const Submitted = meta.story({
  async play({ canvas, userEvent }) {
    const submitButton = canvas.getByRole('button', { name: /submit/i });
    await userEvent.click(saveButton);
    // ๐Ÿ‘‡ Use any mock assertions on the function
    await expect(revalidatePath).toHaveBeenCalledWith('/');
  },
});