0.6.0 • Published 2 months ago

unplugin-msw v0.6.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

unplugin-msw

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

mswunplugin-msw
1.x0.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

setup msw worker

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

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

// unit test
import { server } from 'unplugin-msw/server'

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

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

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

0.6.0

2 months ago

0.4.0

6 months ago

0.3.0

11 months ago

0.2.0

1 year ago

0.1.7

1 year ago

0.1.6

1 year ago

0.1.5

1 year ago

0.1.4

1 year ago

0.1.3

1 year ago

0.1.1

1 year ago

0.1.2

1 year ago

0.1.0

1 year ago