Skip to content

felmonon/msw-inspector

Repository files navigation

msw-inspector

npm version CI Node types license

Find gaps in your API mock coverage before they reach CI.

msw-inspector scans your MSW handlers and your application API calls, compares both sides, and reports what is covered, what is unmocked, and which mocks look stale.

Why this exists

Mock coverage usually decays quietly:

  • a feature adds fetch('/billing') but no matching MSW handler
  • an old handler survives after the app stops calling that endpoint
  • relative URLs and origin-specific URLs drift apart
  • CI can tell you tests passed, but not whether the API surface is still mocked

msw-inspector makes that drift visible. It is intentionally static and conservative: when it cannot understand a dynamic pattern, it reports the pattern as unsupported instead of guessing.

Install

npm install -D msw-inspector-cli

The npm package is published as msw-inspector-cli because msw-inspector is already an active npm package in the MSW ecosystem for runtime request inspection. This project is a static coverage analyzer, and the installed binary remains msw-inspector.

Quick start

Run it from the project root:

npx msw-inspector

Or run it without installing first:

npx msw-inspector-cli

For CI, write the full report and fail on the rules that matter to your project:

npx msw-inspector \
  --report-file msw-inspector.json \
  --format json \
  --min-coverage 80 \
  --fail-on-unmocked

Terminal demo

Screenshot-friendly text output:

$ npx msw-inspector --base-url https://api.example.com --min-coverage 80
✓ 4 handlers found
✓ 6 API calls found
✗ 2 unmocked endpoints
✓ 0 stale mocks

Coverage: 66.7% (4/6)

Unmocked API calls:
  POST /api/chat  src/chat.ts:12
  GET /api/profile  src/profile.ts:33
◌ 1 unsupported patterns skipped

✗ 66.7% mock coverage — 2 unmocked calls

Text output lists up to 10 entries in each detail section—unmocked calls, ambiguous calls, stale handlers, and unsupported patterns. Use --limit <count> to show more or fewer.

Use --format json when you want the full report for CI, dashboards, or the companion GitHub Action.

Matching example

Given these handlers:

import { http } from 'msw'

export const handlers = [
  http.get('/users/:id', () => null),
  http.post('/checkout', () => null),
]

And these API calls:

import axios from 'axios'

await fetch('https://api.example.com/users/123?include=profile')
await axios.post('/checkout')
await fetch('/billing')

msw-inspector reports two covered calls and one unmocked call. Route parameters and query strings are normalized, so /users/:id matches /users/123?include=profile.

If your app uses relative URLs but you want origin-aware matching, set --base-url:

npx msw-inspector --base-url https://api.example.com

That resolves relative handlers and API calls against one canonical origin, which is useful when the same pathname exists on multiple backends.

Useful flags

npx msw-inspector \
  --handlers "src/**/*.{ts,tsx,js,jsx,mts,mjs,cjs}" \
  --sources "src/**/*.{ts,tsx,js,jsx,mts,mjs,cjs}" \
  --exclude "**/dist/**" "**/*.d.ts" \
  --wrappers apiGet apiPost \
  --base-url "https://api.example.com" \
  --report-file msw-inspector.json \
  --format text

Use --wrappers apiGet apiPost (or --wrappers apiGet,apiPost) when request helpers are declared and called in the same file. The scanner resolves each helper's first argument. Names ending in an HTTP verb, such as apiGet or apiPost, use that method; other names are reported with method UNKNOWN. Dynamic arguments remain unsupported instead of being guessed.

For copy-paste setups, see docs/examples/vite-vitest.md for Vite + Vitest and docs/examples/nextjs.md for Next.js.

Common CI gates:

npx msw-inspector --min-coverage 90
npx msw-inspector --fail-on-unmocked
npx msw-inspector --fail-on-stale
npx msw-inspector --fail-on-empty

--fail-on-empty fails when the scan finds no handlers and no API calls, which usually means misconfigured globs or --cwd; an empty scan always prints a warning to stderr.

Exit codes

Code Meaning
0 Analysis ran; no enabled gate failed.
1 A gate failed (--min-coverage, --fail-on-unmocked, --fail-on-stale, --fail-on-empty) or the analysis errored.
2 Usage error: unknown flag or invalid value for --format, --min-coverage, or --limit.

JSON report

The JSON report written by --report-file includes a stable schema version and a summary:

{
  "schemaVersion": 1,
  "summary": {
    "mockedCalls": 23,
    "totalCalls": 31,
    "usedHandlers": 20,
    "totalHandlers": 23,
    "staleHandlers": 3,
    "unmockedCalls": 8,
    "ambiguousCalls": 0,
    "percentage": 74.2
  }
}

Dogfooding

Here is a real run against typejung.com:

Real dogfood run against typejung.com

Dogfood summary:

{
  "summary": {
    "mockedCalls": 0,
    "totalCalls": 24,
    "usedHandlers": 0,
    "totalHandlers": 0,
    "staleHandlers": 0,
    "unmockedCalls": 24,
    "percentage": 0
  },
  "unsupported": 7,
  "sampleUnmocked": [
    "POST https://oauth2.googleapis.com/token",
    "GET https://www.googleapis.com/oauth2/v2/userinfo",
    "POST /api/chat",
    "POST /api/create-checkout-session"
  ]
}

That run surfaced a complete mock gap across auth, billing, and AI endpoints instead of a single missing handler.

All file locations in the report are relative to the scanned directory (--cwd), using forward slashes on every platform, so reports are stable across machines and safe to store as CI baselines.

The full report format is documented in docs/report-schema.md and defined machine-readably in schema/coverage-report.v1.json, which ships with the npm package.

Supported patterns

The first release is intentionally narrow:

  • msw http.* handlers
  • legacy msw rest.* handlers
  • msw graphql.query, graphql.mutation, and graphql.operation handlers (reported with kind: graphql)
  • handler matchers from string literals, static template literals, static consts, new URL(...).href, new URL(...).toString(), and String(new URL(...))
  • fetch(...), window.fetch(...), globalThis.fetch(...), and fetch(new Request(...)) with static arguments
  • common axios call shapes, including axios.get(...), axios.request(...), axios(...), and same-file axios.create(...) instances
  • explicitly configured same-file request wrappers with a static first argument

Unsupported dynamic or ambiguous patterns are included in the report so you can decide whether to simplify the code, add explicit handlers, or ignore the pattern.

GitHub Action

The canonical GitHub Action is felmonon/msw-inspector-action. It reads the JSON report that the CLI already produced, writes a job summary, and can optionally upsert one sticky PR comment.

The action's source lives in this repository under src/github-action/; its built bundle is vendored into the action repository at release time. This repository intentionally does not ship its own action.yml — always use felmonon/msw-inspector-action in workflows.

Marketplace listing: MSW Inspector

name: msw coverage

on:
  pull_request:
  push:

jobs:
  inspect:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci
      - run: npx msw-inspector --report-file msw-inspector.json --format json
      - uses: felmonon/msw-inspector-action@v1
        with:
          summary-file: msw-inspector.json
          comment: true

The action does not compute a baseline delta yet. It publishes the current report cleanly and predictably.

Node API

import { analyzeProject, formatCoverageReport } from 'msw-inspector-cli'

const report = await analyzeProject({
  cwd: process.cwd(),
  baseUrl: 'https://api.example.com',
})

console.log(formatCoverageReport(report))

Limitations

  • It does not resolve imported request wrapper helpers.
  • It does not resolve cross-file constants or imported axios instances.
  • It does not match GraphQL operations to client calls yet, or analyze WebSocket or SSE handlers.
  • It reports dynamic or ambiguous patterns as unsupported instead of guessing.
  • Calls whose HTTP method cannot be resolved statically are reported as ambiguousCalls when their path matches a handler; they never count as mocked or unmocked, and --fail-on-unmocked ignores them.

Project health

Local development

npm install
npm test
npm run typecheck
npm run build

If you are changing the scanning logic, keep the test fixtures small and explicit. The tool is more useful when it stays opinionated.

Contributing

msw-inspector is open to focused contributions that improve real MSW coverage workflows. The strongest issues include a small handler/API-call example, the command that was run, and the expected coverage result.

Start with CONTRIBUTING.md and the roadmap. Good first contributions include framework examples, focused scanner fixtures, clearer unsupported-pattern messages, and docs that help teams add the CLI to CI.

Current open-source focus:

  • Make adoption simple for Vite, Next.js, Vitest, Playwright, and GitHub Actions users.
  • Improve static scanner precision without guessing dynamic runtime behavior.
  • Keep the JSON report and GitHub Action output stable enough for CI.

About

CLI and GitHub Action that finds gaps between MSW handlers and real API usage.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors