CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-msw-storybook-addon

Mock API requests in Storybook with Mock Service Worker.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

initialization.mddocs/

MSW Initialization

Core MSW initialization functionality that sets up Mock Service Worker for the appropriate platform (browser, Node.js, or React Native). The package automatically selects the correct implementation based on the target environment.

Capabilities

Initialize Function

Sets up MSW worker or server with optional configuration and initial request handlers.

// MSW types imported from 'msw'
import type { RequestHandler } from 'msw';
import type { SetupWorker } from 'msw/browser';
import type { SetupServer } from 'msw/node';

/**
 * Initialize MSW for the current platform
 * @param options - Platform-specific configuration options
 * @param initialHandlers - Optional array of request handlers to register immediately
 * @returns SetupWorker (browser) or SetupServer (Node.js/React Native)
 */
function initialize(
  options?: InitializeOptions,
  initialHandlers?: RequestHandler[]
): SetupWorker | SetupServer;

Usage Examples:

import { initialize } from "msw-storybook-addon";
import { http, HttpResponse } from "msw";

// Basic initialization
initialize();

// With initial handlers
const handlers = [
  http.get("/api/users", () => {
    return HttpResponse.json([{ id: 1, name: "John" }]);
  }),
];
initialize({}, handlers);

// With configuration options (browser)
initialize({
  serviceWorker: {
    url: '/custom-mockServiceWorker.js'
  }
});

// With configuration options (Node.js)
initialize({
  onUnhandledRequest: 'error'
});

Initialize Options Type

Platform-specific configuration options for MSW initialization.

type InitializeOptions = 
  | Parameters<SetupWorker['start']>[0]  // Browser platform
  | Parameters<SetupServer['listen']>[0]; // Node.js/React Native platforms

Browser Options (SetupWorker['start'] parameters):

  • serviceWorker?: { url?: string; options?: RegistrationOptions }
  • findWorker?: (scriptURL: string, mockServiceWorkerUrl: string) => boolean
  • onUnhandledRequest?: 'bypass' | 'warn' | 'error' | ((req: MockedRequest, print: RequestPrint) => void)
  • waitUntilReady?: boolean

Node.js/React Native Options (SetupServer['listen'] parameters):

  • onUnhandledRequest?: 'bypass' | 'warn' | 'error' | ((req: MockedRequest, print: RequestPrint) => void)

Get Worker Function

Returns the currently active MSW worker or server instance.

/**
 * Get the current MSW worker/server instance
 * @returns SetupWorker (browser) or SetupServer (Node.js/React Native)
 * @throws Error if no worker is initialized
 */
function getWorker(): SetupWorker | SetupServer;

Usage Example:

import { initialize, getWorker } from "msw-storybook-addon";
import { http, HttpResponse } from "msw";

// Initialize first
initialize();

// Get the worker instance
const worker = getWorker();

// Use worker methods
worker.use(
  http.get("/api/dynamic", () => {
    return HttpResponse.json({ dynamic: true });
  })
);

Platform-Specific Behavior

Browser Platform

  • Uses setupWorker from msw/browser
  • Creates and starts a service worker
  • Supports service worker activation
  • Returns SetupWorker instance

Node.js Platform

  • Uses setupServer from msw/node
  • Starts an intercepting server
  • Activation is instant upon registration
  • Returns SetupServer instance

React Native Platform

  • Uses setupServer from msw/native
  • Starts native request interception
  • Activation is instant upon registration
  • Returns SetupServer instance

Error Handling

The getWorker() function throws an error if called before initialization:

[MSW] Failed to retrieve the worker: no active worker found. Did you forget to call "initialize"?

Internal Implementation Details

The addon automatically filters certain requests to reduce noise in Storybook:

  • Static assets (.js, .css, fonts, etc.)
  • Storybook-specific requests (sb-common-assets, iframe.html, etc.)
  • Build tool requests (webpack HMR, Vite, etc.)
  • Story and documentation files (.stories., .mdx)

This filtering can be customized via the onUnhandledRequest option in InitializeOptions.

docs

index.md

initialization.md

storybook-integration.md

worker-management.md

tile.json