MSW

GingerBook has a build-in support for MSW v2. It allows API mocking by intercepting requests on the network level.

You just have to enable it in your .ginger-book/config.mjs:

/** @type {import('@ginger-society/ginger-book').UserConfig} */
export default {
  addons: {
    msw: {
      enabled: true,
    },
  },
};

GingerBook automatically sets up the MSW service worker for you - copying it over into the public folder. GingerBook also re-exports MSW library so you don’t have to install it yourself.

Usage

import type { Story } from "@ginger-society/ginger-book";
import { msw } from "@ginger-society/ginger-book";
import { useEffect, useState } from "react";

const FETCH_URL = "/api-url.json";

// Set default handlers for all stories
export default {
  msw: [
    msw.http.get(FETCH_URL, () => {
      return msw.HttpResponse.json([{ id: 1, title: "msw post default" }]);
    }),
  ],
};

export const Mocked: Story = () => {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    try {
      const data = await fetch(FETCH_URL);
      const json = await data.json();
      setPosts(json);
    } catch (e) {
      console.error(e);
    }
  }, []);
  return (
    <>
      <h1>Posts</h1>
      <ul>
        {posts.map((post: { id: number; title: string }) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </>
  );
};

// handlers for this story only
// Mocked.msw = [];

You can also use MSW to mock GraphQL requests. Check their documentation.

Import msw/node

When you need to setup node environment for MSW, you would use:

import { setupServer } from 'msw/node'

You can use the GingerBook’s version of MSW by using this import instead:

import { setupServer } from "@ginger-society/ginger-book/msw-node";