Skip to content
MSW logo

MSW

Officialv6.2.6

@kubb/plugin-msw

kubb add plugin-msw

Mock API responses

Generate typed MSW handlers and register them in tests or a browser worker.

Generate the handlers

Add pluginTs and pluginMsw to kubb.config.ts, then run kubb generate. Pick where the response body comes from:

The default parser: 'data' returns the data you pass.

kubb.config.ts
import { defineConfig } from 'kubb/config'
import { pluginTs } from '@kubb/plugin-ts'
import { pluginMsw } from '@kubb/plugin-msw'

export default defineConfig({
  input: './petStore.yaml',
  output: { path: './src/gen' },
  plugins: [
    pluginTs(),
    pluginMsw({ output: { path: 'handlers', mode: 'directory' }, baseURL: 'http://localhost:3000', handlers: true }),
  ],
})
For Node tests, set baseURL to the URL your client calls, so MSW matches absolute requests. In the browser, relative paths match the current origin.

Register the handlers

With handlers: true, handlers.ts exports every handler as handlers.

import { setupServer } from 'msw/node'
import { handlers } from './src/gen/handlers/handlers'

export const server = setupServer(...handlers)

Call server.listen() in your test setup, or await worker.start() in your browser entry.

Supply test data

Call a handler with a response body, or with a callback that returns a Response.

test-server.ts
import { setupServer } from 'msw/node'
import { getPetByIdHandler } from './src/gen/handlers/getPetByIdHandler'

export const server = setupServer(
  getPetByIdHandler({ name: 'Rex', photoUrls: [] }),
)

Set the base URL at runtime

Kubb sets the baseURL option at generation time. When you know the host only at runtime, pass it to createHandlers:

test-server.ts
import { setupServer } from 'msw/node'
import { createHandlers } from './src/gen/handlers/handlers'

export const server = setupServer(...createHandlers({ baseURL: getBaseURL() }))

Each handler also takes { baseURL } as its second argument. Pass undefined as the first argument to keep the default response, for example to mock two services that share a path:

test-server.ts
export const server = setupServer(
  listPetsHandler(undefined, { baseURL: 'https://pets.example.com' }),
  listPetsHandler(undefined, { baseURL: 'https://staging.example.com' }),
)

For every handler option, see the MSW options.

Less common cases

Examples from the spec

With parser: 'data', a handler called without data sends the first example of the success response, when the spec has one.

  • Kubb reads the example's value, else its serializedValue.
  • A serializedValue is parsed for a JSON response and sent as is for a text response.
  • Pass null to send a null body instead of the example.

When you pass data, the handler returns it through new HttpResponse(JSON.stringify(data), ...), typed with the @kubb/plugin-ts types.