unplugin-msw
TypeScript icon, indicating that this package has built-in type declarations

0.6.0 • Public • Published

unplugin-msw

unplugin-msw is a utility plugin that simplifies msw setup and commonizes "worker" and "server" mocks.

msw unplugin-msw
1.x 0.3.0
2.x >= 0.4.0

Feature

  • msw worker and server creation can be simplified
  • mocks can be easily shared and switched between worker and server

Install

npm i -D unplugin-msw

Vite

// vite.config.ts
import MswPlugin from 'unplugin-msw/vite'

export default defineConfig({
  plugins: [
    MswPlugin(),
    // or
    MswPlugin({
      // default
      mockDir: 'mock/handlers', // handler definition directory
      workerEnabled: process.env.NODE_ENV === 'development', // worker startup condition
    })
  ],
})

Example: playground/

WIP: esbuild, rollup, webpack...

Setup

install msw

msw handler definition

Two types of definitions are available: the normal msw handler definition and an extended definition. The normal definition is common to both servers and workers, while the extended definition allows the choice of server or worker.

[!WARNING] Creates a handler that combines all files under the specified directory. Each handler should be exported by default.

import { HttpResponse, http } from 'msw'
import type { UnpluginMswHandlers } from 'unplugin-msw/types'

export default [
  // mws definition, use server and worker
  http.get('https://my-handle-url', () => {
    return HttpResponse.json({
      key: 'value',
    })
  }),
  // use worker only
  {
    handler: http.get('https://worker-only', () => {
      return HttpResponse.json({
        key: 'value',
      })
    }),
    type: 'worker',
  },
  // use server only
  {
    handler: http.get('https://server-only', () => {
      return HttpResponse.json({
        key: 'value',
      })
    }),
    type: 'server',
  },
] as UnpluginMswHandlers

use worker or server

worker (for frontend)

setup msw worker

import { worker } from 'unplugin-msw/worker'

// worker is undefined when 'workerEnabled' === false
worker?.start()


server (for server, unit test)
// unit test
import { server } from 'unplugin-msw/server'

beforeAll(() => {
  server.listen()
})

afterAll(() => {
  server.close()
})


server (for vitest)
import { setupVitest } from 'unplugin-msw/server/vitest'

/**
 * setupVitest is shorthand
 * () => {
 *   beforeAll(() => server.listen())
 *   afterEach(() => server.resetHandlers())
 *   afterAll(() => server.close())
 * }
 */
setupVitest()


TypeScript

{
  "compilerOptions": {
    "types": [
      "unplugin-msw/globals"
    ]
  }
}

Credit

Package Sidebar

Install

npm i unplugin-msw

Weekly Downloads

16

Version

0.6.0

License

MIT

Unpacked Size

66.1 kB

Total Files

43

Last publish

Collaborators

  • esttom