2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

msw-storybook-addonでグローバルなAPIモックを作成する方法

Posted at

環境

"next": "13.1.1",
"react": "18.2.0",
"msw": "^1.2.2",
"msw-storybook-addon": "^1.8.0",
"storybook": "^7.0.12",
"typescript": "4.9.4"

手順

1. 以下のコマンドを実行して、msw-storybook-addonをプロジェクトに追加する。

bash
npm install --save-dev msw msw-storybook-addon
#または
yarn add --dev msw msw-storybook-addon

2. プロジェクトのpublicフォルダでサービスワーカーファイルを生成する。

bash
npx msw init public/

3../storybook/preview.tsx に下記のように作成したいAPIモックを追記する。

preview.tsx
// 省略...

// Initialize MSW
initialize();

const preview = {
  parameters: {
    // 省略...
    },
    msw: {
      handlers: [
        rest.get("/api/current", async (_, res, ctx) => {
          return res(
            ctx.status(200),
            ctx.json({
              id: 1,
              bio: "フロントエンドエンジニア。TypeScriptとNextに興味があります。",
              location: "Tokyo, Japan",
              name: "TaroYamada",
              profileImageUrl: "/__mocks__/images/img01.png",
              username: "@taro_yamada",
              website: "https://taro_yamada.com",
            })
          );
        }),
      ],
    },
  },
  decorators: [
    // 省略...
  ],
  loaders: [mswLoader],
};

export default preview;

4.APIモックを使用したいコンポーネントで下記のようなコードを追記

Profile.tsx
useEffect(() => {
  fetch("/api/current")
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      return setCurrentUser(data);
    });
}, []);

ちなみにStoryファイル自体はこんな感じ。

Profile.stories.tsx
// 省略...

const meta: Meta<typeof Profile> = {
  component: Profile,
  tags: ["autodocs"],
  title: "Profile",
};

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

export const Default: Story = {};
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?