#LearnedToday: MSWjs

Daniel Zotti - Jul 10 '23 - - Dev Community

Do you need to reuse the same mock definition for testing, development, and debugging?

Try Mock Service Worker!

It’s a library that uses Service Worker API to intercept requests on the network level and it replies with your mock data.

Just install it

npm install msw --save-dev
Enter fullscreen mode Exit fullscreen mode

and configure your APIs:

// src/mocks/handlers.js
import { setupWorker, rest } from 'msw'

const worker = setupWorker(
  rest.post('/login', async (req, res, ctx) => {
    const { username } = await req.json()

    return res(
      ctx.json({
        username,
        firstName: 'John'
      })
    )
  }),
)

worker.start()
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player