0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vite + React 環境の Storybook でモジュールをモックする方法

Last updated at Posted at 2025-05-04

はじめに

vite環境のStorybookでモジュールをモックする方法です。

💡ポイント
vitestではモックを行う際に、vi.spyOnvi.mockを定義してモックするが、
Storybookではモックファイルを利用してモックを行う。

Qiita.png

参考資料

サンプルコード

importしたuuidを表示するだけのページ。

スクリーンショット 2025-05-05 3.05.31.png

uuid.ts
export const uuid = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
index.tsx
import { Container } from '@mui/material';
import { uuid } from 'app/lib/uuid';

export const Sample = () => {

    return (
        <Container>
            <div>
                <h1>UUID</h1>
                <p>これはUUIDを表示するコンポーネントです</p>
                <p>{uuid}</p>
            </div>
        </Container>
    );
}

モック

モックファイル

モックファイルを用意する。

uuid.mock.ts
export const uuid = 'mockmock-mock-mock-mock-mockmockmock';

コンフィグ

vite.storybook.config.tsファイルにaliasを設定する。

以下のように記載することで、
'app/lib/uuid'をimportするコンポーネントで、
'app/lib/uuid.mock.ts'がimportされるようになる。

vite.storybook.config.ts
 import { defineConfig, loadEnv } from 'vite';
 import tsconfigPaths from 'vite-tsconfig-paths';
+import { resolve } from 'path';
 
 export default defineConfig(({ mode }) => {
     const env = loadEnv(mode, process.cwd(), '');
     process.env = { ...process.env, ...env };
     return {
         plugins: [tsconfigPaths()],
+        resolve: {
+            alias: {
+                // 'uuid'をimportするコンポーネントで、
+                // 'uuid.mock.ts'がimportされるようになる
+                'app/lib/uuid': resolve(__dirname, 'app/lib/uuid.mock'),
+            },
+        },
     };
 });

Qiita (1).png

Storybook

stories.tsx

stories.tsxを用意する。
(モックを利用するための設定などは不要)

index.stories.tsx
import { Sample } from './index';
import type { Meta, StoryObj } from '@storybook/react';

const meta = {
    title: 'Features/Sample',
    component: Sample,
    parameters: {
        layout: 'fullscreen',
    },
} satisfies Meta<typeof Sample>;

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

export const Default: Story = {};

Storybook
Storybookを起動する。

$ npm run storybook

Storybook上ではモックファイルがimportされるようになる。

スクリーンショット 2025-05-05 3.05.24.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?