0
0

More than 3 years have passed since last update.

Mock Service Workertつかってみた

Posted at

Mock Service Workerをつかうと、簡単にhttpレスポンスのモックテストができるのでやってみました。

参考ページ
翻訳すればいける、ここぐらいしか記述が無い。。
https://mswjs.io/docs/basics/request-matching

チュートリアルとあわせてみると理解が深まる
https://www.wakuwakubank.com/posts/765-react-mock-api/

index.js
サービスの起動、ここでリクエストがあった場合に返すレスポンスを決める

import { setupWorker, rest } from 'msw'

const worker = setupWorker(
  rest.get('/users/:userId', (req, res, ctx) => {
    const { userId } = req.params
    return res(
      ctx.json({
        id: userId,
        firstName: 'John',
        lastName: 'Maverick',
      }),
    )
  }),
)
worker.start()

呼び出し元、下記で呼び出す(やり方は何でもOK

const response2 = await fetch("/users/500")
        .then((response) => response.json())
        .then((data) => data);

mocksの中のjsも一応

// src/mocks/browser.js
import { setupWorker } from "msw";
import { handlers } from "./handlers";
// This configures a Service Worker with the given request handlers.
export const worker = setupWorker(...handlers);


// 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",
      })
    );
  }),
];

注意点として

公式チュートリアルのTroubleshootingを見ておくと良い

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