Use when user has a HAR file and wants to create API mocks, or when setting up MSW mocking for tests/Storybook from network recordings.
Extract JSON mocks from HAR files and integrate with MSW for testing and Storybook.
HAR File → har-to-mocks → JSON Mocks → mocks-to-msw → MSW Handlers → Storybook/Tests
npx har-to-mocks recording.har ./src/mocks --interactive
npx mocks-to-msw generate ./src/mocks
// src/mocks/handlers.ts
import { createMockHandler } from 'mocks-to-msw';
import { mocks } from './mocks';
export const { mock, handlers } = createMockHandler<keyof typeof mocks>({
mocks,
debug: true,
});
npx msw init ./public --save
User: "I have a network.har file, extract the API mocks from it"
Action:
npx har-to-mocks network.har ./src/mocks --interactive
npx mocks-to-msw generate ./src/mocks
Output: "Extracted 12 endpoints to ./src/mocks and generated mocks.ts registry."
User: "Set up the mocks to work with Storybook"
Action:
npm install msw-storybook-addon --save-dev.storybook/main.ts:addons: ['msw-storybook-addon'],
staticDirs: ['../public'],
.storybook/preview.tsx:import { initialize, mswLoader } from 'msw-storybook-addon';
import { handlers } from '../src/mocks/handlers';
initialize();
export default {
parameters: { msw: { handlers } },
loaders: [mswLoader],
};
Output: "Configured MSW addon for Storybook. Mocks are now active in all stories."
User: "Extract only POST requests to /api/users from the HAR"
Action:
npx har-to-mocks recording.har ./src/mocks --url "/api/users" --method POST
Output: "Extracted POST /api/users endpoint to ./src/mocks/api/users/POST.json"
User: "I want to show an error state in my UserList story"
Action: Add to story file:
export const WithError: Story = {
parameters: {
msw: {
handlers: [
http.get('*/api/users', () => HttpResponse.json(null, { status: 500 })),
],
},
},
};
Output: "Added error handler override. The story now displays the error state."
| Command | Description |
|---|---|
npx har-to-mocks <har> <output> --interactive |
Interactive endpoint selection |
npx har-to-mocks <har> <output> --url <pattern> |
Filter by URL |
npx har-to-mocks <har> <output> --method <GET|POST|...> |
Filter by HTTP method |
npx har-to-mocks <har> <output> --dry-run |
Preview without writing |
npx mocks-to-msw generate <mocks-dir> |
Generate type-safe imports |
See REFERENCE.md for detailed documentation including: