Closed16

MSWの門前

hajimismhajimism
hajimismhajimism

実際のモックの実装は src/mocks/resolvers 配下に REST API のリソースごとにファイルを配置し、src/mocks/handler.ts ではどのリクエストをどのハンドラに対応させるかの記述をするのがよい感じです。

src/mocks/
├── browser.ts
├── handler.ts
├── resolvers
│   ├── login.ts
│   ├── logout.ts
│   ├── posts.ts
│   └── users.ts
└── server.ts

もはや必須のやつ

hajimismhajimism

JSON レスポンスを返却する ctx.json() メソッドは型引数を受け取ることができます。ctx.json() の引数が型引数と一致しない場合には、型エラーが発生します。

hajimismhajimism

ようやくちゃんと読む
https://mswjs.io/docs/

hajimismhajimism

そもそもService Workerとは

Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API

hajimismhajimism

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and Web Storage can't be used inside a service worker.

hajimismhajimism

Why Service Workers?
Mock Service Worker leverages a standardized Service Worker API that is designed to intercept requests on the network level, making the mocking completely seamless. Not only this guarantees an identical application's behavior with and without mocks, but also does not require any changes to the application's code for the sake of mocking. Observe requests in the "Network" of your DevTools, forgetting the mocks are at place.

たしかにネットワークレベルでモックされていればテストのためにコードをどうこうする心配は大幅に削減される

hajimismhajimism

例 (cited from: https://mswjs.io/docs/getting-started/mocks/rest-api )

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

export const handlers = [
  rest.post('/login', (req, res, ctx) => {
    // Persist user's authentication in the session
    sessionStorage.setItem('is-authenticated', 'true')

    return res(
      // Respond with a 200 status code
      ctx.status(200),
    )
  }),

  rest.get('/user', (req, res, ctx) => {
    // Check if the user is authenticated in this session
    const isAuthenticated = sessionStorage.getItem('is-authenticated')

    if (!isAuthenticated) {
      // If not authenticated, respond with a 403 error
      return res(
        ctx.status(403),
        ctx.json({
          errorMessage: 'Not authorized',
        }),
      )
    }

    // If authenticated, return a mocked user details
    return res(
      ctx.status(200),
      ctx.json({
        username: 'admin',
      }),
    )
  }),
]
このスクラップは2023/01/20にクローズされました