0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Mock Service Workとは?

Last updated at Posted at 2023-03-08

msw(Mock Service Work)とは

mock(模擬データ)を作って活用する方式です。
通常、data fetchを行う必要がある場合は、応答を返すサーバが必要です。
実務の場合、サーバapiが既に用意されている為mockデータが不要かもしれないが、
まだ開発中とかAPIがない場合、フロント開発にもっと集中するためにデータサーバーを別に作らずにmockigを活用するのに これらのタスクをサポートするライブラリ! クライアントからのリクエストをmswが自ら受け、自ら応答を返します。

mockingを使ってみる

mswjs examplesは以下のそれぞれのService Worker Apiを使って、mockingを学習することができます。
image.png

rest-react example

MockServiceWorkerを使用してRESTAPIをモックする方法を説明しています。

rest-reactでは、post requestを奪ってjsonのresponseを返却します。
'/login'というrequestが来ると、それをinterceptして、return res()を返すとの意味です。

mocks/handler.js
import { rest } from 'msw'

export const handlers = [
  rest.post('/login', (req, res, ctx) => {
    const { username } = JSON.parse(req.body)
    
    return res(
      ctx.json({
        id: 'f79e82e8-c34a-4dc7-a49e-9fadc0979fda',
        firstName: username,
        lastName: 'Maverick',
      })
    )
  }),
]

post request
image.png

response!ctx.jsonに設定してあるデータが返却されます。
image.png

graphql

MockServiceWorkerを使用してGraphQLAPIをモックする方法を示しています。 GraphQLAPIでは、mutation requestを奪ってjsonのresponseを返却します。 (mutaion == post)
今のresponseロジックはどんなrequestに対しても同じデータを返却するようになっています。 これも同じく、'Login'requestをinterceptして return res()を返すとの意味になります。
mocks/handlers.js
import { graphql } from 'msw'

export const handlers = [
  // Capture a "Login" mutation
  graphql.mutation('Login', (req, res, ctx) => { 
    const { username } = req.variables

    if (username === 'non-existing') {
      return res(
        ctx.errors([
          {
            message: 'User not found',
            extensions: {
              id: 'f79e82e8-c34a-4dc7-a49e-9fadc0979fda',
            },
          },
        ])
      )
    }

    return res(
      ctx.data({
        user: {
          __typename: 'User',
          id: 'f79e82e8-c34a-4dc7-a49e-9fadc0979fda',
          firstName: 'John',
          lastName: 'Maverick',
        },
      })
    )
  }),
]

post request
image.png

response
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?