文件
Storybook 文件

模擬提供器

元件可以從內容提供器接收資料或設定。例如,樣式化的元件可能會從 ThemeProvider 存取其主題,或者 Redux 使用 React 內容來提供元件存取應用程式資料。若要模擬提供器,您可以將您的元件包裝在包含必要內容的裝飾器中。

.storybook/preview.tsx
import React from 'react';
 
import { Preview } from '@storybook/react';
 
import { ThemeProvider } from 'styled-components';
 
const preview: Preview = {
  decorators: [
    (Story) => (
      <ThemeProvider theme="default">
        {/* 👇 Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it  */}
        <Story />
      </ThemeProvider>
    ),
  ],
};
 
export default preview;

請注意上方的檔案副檔名 (.tsx.jsx)。您可能需要調整預覽檔案的副檔名,以允許使用 JSX,具體取決於您的專案設定。

另一個範例,請參考 Storybook 教學簡介的畫面章節,其中我們使用模擬資料模擬 Redux 提供器。

設定模擬提供器

在模擬提供器時,可能需要設定提供器,以便為個別故事提供不同的值。例如,您可能想要測試具有不同主題或使用者角色的元件。

一種方式是針對每個故事個別定義裝飾器。但是,如果您想像一下希望為每個元件建立淺色和深色主題的故事的狀況,這種方法可能會很快變得麻煩。

若要獲得更好的方式,並減少重複,您可以使用裝飾器函數的第二個 "context" 引數來存取故事的parameters,並調整提供的值。如此一來,您就可以定義一次提供器,並調整每個故事的值。

例如,我們可以從上方調整裝飾器,以便從 parameters.theme 讀取,以判斷要提供哪個主題

.storybook/preview.tsx
import React from 'react';
 
import type { Preview } from '@storybook/react';
import { ThemeProvider } from 'styled-components';
 
// themes = { light, dark }
import * as themes from '../src/themes';
 
const preview: Preview = {
  decorators: [
    // 👇 Defining the decorator in the preview file applies it to all stories
    (Story, { parameters }) => {
      // 👇 Make it configurable by reading the theme value from parameters
      const { theme = 'light' } = parameters;
      return (
        <ThemeProvider theme={themes[theme]}>
          <Story />
        </ThemeProvider>
      );
    },
  ],
};
 
export default preview;

現在,您可以在您的故事中定義 theme 參數,以調整裝飾器提供的主題

Button.stories.ts
import type { Meta, StoryObj } from '@storybook/react';
 
import { Button } from './Button';
 
const meta: Meta<typeof Button> = {
  component: Button,
};
export default meta;
 
type Story = StoryObj<typeof Button>;
 
// Wrapped in light theme
export const Default: Story = {};
 
// Wrapped in dark theme
export const Dark: Story = {
  parameters: {
    theme: 'dark',
  },
};

這種強大的方法可讓您以彈性且可維護的方式,為元件提供任何值 (主題、使用者角色、模擬資料等)。