MSW(Mock Service Worker)
- 테스트코드 강의를 들으면서 사용해보게 된
MSW(Mock Service Worker)
에 대해 간단히 정리해보았다.
MSW란?
Mock Service Worker
의 준말로, 이를 사용하면 실제 api를 호출하지 않고 데이터를 요청할 수 있다. 정확하게 말하자면 api 요청을 가로챈 후 service worker가 mocking data를 전달해주는 것이다. (Service Worker의 가짜 데이터를 넘겨준다.)- 애플리케이션 내부에 직접 Mock데이터를 심거나 Mock 서버를 별도로 만들 필요 없이 실제 API를 사용하는 것처럼 네트워크 수준에서 Mocking이 가능하다.
MSW Request Flow
msw
라이브러리를 통해 애플리케이션의 네트워크 요청을 감지하여mocking
된 응답을 전달할 수 있는Service Worker
를 사용할 수 있게 된다.
MSW Install
npm install msw --dev
# or
yarn add msw --dev
Define mocks
request
및mocked response
를 설정해주는 단계이다. 공식문서에 아주 자세하게 잘 나와있다.
1. REST API 기준 세팅
// src/mock/handlers.ts
// library imports
import { rest } from "msw";
// Request handler, Response resolver
export const handlers = [
rest.get("http://localhost:3030/scoops", (req, res, ctx) => {
return res(
ctx.json([
{ name: "Chocolate", imagePath: "/images/chocolate.png" },
{ name: "Vanilla", imagePath: "/images/vanilla.png" },
])
);
}),
rest.get("http://localhost:3030/toppings", (req, res, ctx) => {
return res(
ctx.json([
{ name: "Cherries", imagePath: "/images/cherries.png" },
{ name: "M&Ms", imagePath: "/images/m-and-ms.png" },
{ name: "Hot fudge", imagePath: "/images/hot-fudge.png" },
])
);
}),
];
- rest[METHOD]를 통해
request handlers
를 설정해줄 수 있다. (여러개의request
를 생성하고자 할 경우, 배열 형태로 지정하여 사용할 수 있다.) req
: 매칭된request
에 대한 정보이다.res
:mocking
된response
를 생성하기 위한 함수이다.ctx
:status code
,headers
,body
등mocking
된response
을 세팅하기 위한 함수의 그룹이다.
Browser Integration
browser
에서msw
가 동작하기 위해 추가 설정이 필요하다. (node
버전도 존재하며 자세한건 공식문서를 참고하도록 하자.)
Install
npx msw init ./public --save
ConFigure Worker
// src/mock/browser.ts
import { setupWorker } from "msw";
import { handlers } from "./handlers";
// This configures a Service Worker with the given request handlers.
export const worker = setupWorker(...handlers);
msw
가 동작하기 위해configure
파일인browser.ts
파일을 생성해준다.
Start Worker
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "bootstrap/dist/css/bootstrap.min.css";
import { GlobalStyle, theme } from "src/styles";
import { ThemeProvider } from "styled-components";
if (process.env.NODE_ENV === "development") {
const { worker } = require("src/mocks/browser");
worker.start();
}
ReactDOM.render(
<React.StrictMode>
<GlobalStyle />
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</React.StrictMode>,
document.getElementById("root")
);
dev mode
의 런타임 환경에서 정상적으로 동작하기 위해index.ts
파일을 설정해준다.
결과 확인
- 위 사진에서 보이는,
[MSW] Mocking enabled
메시지를 통해 정상적으로 작동하는 것을 알 수 있다.
Reference
'Etc' 카테고리의 다른 글
TIL | Tailwind CSS (0) | 2022.03.10 |
---|---|
TIL | Webstorm IDE Setting Share (0) | 2022.03.01 |
TIL | git 폴더명 대소문자 이슈 (0) | 2022.01.29 |
TIL | testing-library, Jest-Dom eslint 설정하기 (0) | 2022.01.15 |
TIL | Atomic design pattern 간단 정리 (0) | 2022.01.10 |