React์—์„œ์˜ MSW ๊ธฐ๋ณธ ์‚ฌ์šฉ๋ฒ•

โค๏ธโ€๐Ÿ”ฅMSW ์†Œ๊ฐœ

MSW(mocking service worker)๋Š” API๋ฅผ mockingํ•  ์ˆ˜ ์žˆ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ž…๋‹ˆ๋‹ค.

mocking์˜ ์žฅ์ 

  1. ํ…Œ์ŠคํŠธ ์ฝ”๋“œ์˜ ์˜์กด์„ฑ์„ ๋œ์–ด๋‚ด ๋…๋ฆฝ์ ์ธ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  2. ์‹ค์ œ ์‘๋‹ต์„ ๊ธฐ๋‹ค๋ฆฌ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—, ์†๋„ ์ธก๋ฉด์—์„œ ๋น„์šฉ์ ˆ๊ฐ์ด ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

โ—๏ธMSW๋ฅผ React์—์„œ ์‚ฌ์šฉํ•ด๋ณด์ž.

  1. ์šฐ์„  msw๋ฅผ ์„ค์น˜ํ•ด์ค๋‹ˆ๋‹ค. npm install msw@latest --save-dev

  2. ๊ทธ ๋‹ค์Œ msw๋ฅผ ์‹คํ–‰ํ•ด์ค์‹œ๋‹ค. npx msw init public/ --save

  3. "msw": { "workerDirectory": [ "public" ] }

  4. ์ด ๊ฒฐ๊ณผ๋กœ package.json์— ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์Šคํฌ๋ฆฝํŠธ๊ฐ€ ์ถ”๊ฐ€๋ฉ๋‹ˆ๋‹ค.

  5. ์„ธํŒ…์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด์ œ mocking ๋ชจ๋“ˆ์„ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.
    ํŒŒ์ผ ๋””๋ ‰ํ† ๋ฆฌ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

    src/mocks
    โ”œโ”€โ”€ browser.ts
    โ”œโ”€โ”€ dummy.json
    โ””โ”€โ”€ handlers.ts

    ์ €๋Š” dummy.json์ด๋ผ๋Š” ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด ์‚ฌ์šฉํ•˜์˜€์Šต๋‹ˆ๋‹ค.

    // src/mocks/handlers.ts
    import { HttpResponse, http } from "msw";
    import dummy from "./dummy.json";
    
    export const handlers = [
      http.get("/dummy", () => {
        return HttpResponse.json(dummy);
      }),
    ];
    // src/mocks/dummy.json
    [
      {
        "id": "1",
        "name": "kim"
      },
      {
        "id": "2",
        "name": "lee"
      },
      {
        "id": "3",
        "name": "park"
      }
    ]
    // src/mocks/browser.ts
    import { setupWorker } from "msw/browser";
    import { handlers } from "./handlers";
    
    export const worker = setupWorker(...handlers);
  6. React์˜ main.tsx๋ฅผ ์ˆ˜์ •ํ•ด์ค์‹œ๋‹ค. dev๋ชจ๋“œ ์—์„œ๋งŒ mocking์„ ์‚ฌ์šฉํ•˜๋„๋ก ํ•˜๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

     // main.tsx
     import React from "react";
     import ReactDOM from "react-dom/client";
     import App from "./App.tsx";
    
     async function enableMocking() {
       if (process.env.NODE_ENV !== "development") {
         return;
       }
    
       const { worker } = await import("./mocks/browser"); //Dynamic importํ•˜๋Š” ๊ฒƒ์ด ๋ˆˆ์— ๋„์˜€๋‹ค.
       return worker.start();
     }
    
     enableMocking().then(() => {
       ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
         <React.StrictMode>
           <App />
         </React.StrictMode>
       );
     });

์ •์ƒ์ ์œผ๋กœ ๋ชจํ‚น์ด ์™„๋ฃŒ๋˜์—ˆ์„ ๋•Œ ์ฝ˜์†”์ฐฝ

โ—๏ธ์š”์•ฝ

  1. msw๋ชจ๋“ˆ์„ ์„ค์น˜ํ•˜๊ณ  handler๋ฅผ ๋งŒ๋“ค์–ด ์ค€๋‹ค.
  2. ์ด ํ•ธ๋“ค๋Ÿฌ๋Š” msw/browser๋ชจ๋“ˆ์— ์žˆ๋Š” setupWorker์˜ start๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด์„œ ์‹คํ–‰์‹œ์ผœ ์ค€๋‹ค.
  3. ์‹คํ–‰ํ•œ๋‹ค๋ฉด ํ•ด๋‹น ์š”์ฒญ์€ mocking์ด ๋œ๋‹ค.