MSW
Mock Service Worker
๋คํธ์ํฌ ๊ณ์ธต์ ๋ชฉ ๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
์น API ์์ฒญ์ ๊ฐ๋ก์ฑ์ ์์์ ๊ฐ์ผ๋ก ๋ง๋ ์๋ต์ผ๋ก ๋์ฒด
์์ฑ๋ ์์ฒญ์
headers,query์ ์ธ๋ถ ๋ด์ฉ์ ๊ฒ์ฆ ๋ํ ๊ฐ๋ฅ
์น API ์๋ฒ๋ฅผ ์คํํ์ง ์์๋ ์๋ต ์ฌํ ๊ฐ๋ฅ
์น API ์์ฒญ์ ๊ฐ๋ก์ฑ๋ ค๋ฉด ์์ฒญ ํธ๋ค๋ฌ๋ฅผ ๋ง๋ค์ด์ผํ๋ค.
๋ธ๋ผ์ฐ์ ๋ ์๋ฒ ๋ฑ ์ด๋์์ ์์ฑ๋ ์์ฒญ์ธ์ง ๊ด๊ณ์์ด ์์ฒญ์ ๊ฐ๋ก์ฑ ์ ์์ด BFF๋ฅผ ํฌํจํ ๋ค์ํ ํ๋ก ํธ์๋ ํ ์คํธ ํ๊ฒฝ์์ ํ์ฉ ๊ฐ๋ฅ
import { setupWorker, rest } from 'msw';
const worker = setupWorker(
rest.post("/login", async (req, res, ctx) => {
const { username } = await req.json();
return res(
ctx.json({
username,
firstName: "John",
})
)
})
);
worker.start();
// setupServer
// server.ts
import { setupServer } from "msw/node";
import handlers from "./handlers";
const server = setupServer(...handlers);
export default server;
// handlers.ts
import { rest } from "msw";
import * as fixtures from "@/fixtures";
const handlers = [
rest.get("/categories", (req, res, ctx) =>
res(ctx.json({ categories: fixtures.categories }))
),
rest.get("/products", (req, res, ctx) => {
const categoryId = req.url.searchParams.get("categoryId");
if (categoryId) {
return res(
ctx.json({
products: fixtures.products.filter(
(product) => product.category.id === (categoryId as string)
),
})
);
}
return res(ctx.json({ products: fixtures.products }));
})]Jest์ฉ ์ธํ
setupTests.ts์์ ํ ์คํธ์ ์ค์ ์ ๊ธ๋ก๋ฒ ๊ด๋ฆฌ
// eslint-disable-next-line import/no-extraneous-dependencies
import "@testing-library/jest-dom";
import "whatwg-fetch";
import server from "./mocks/server";
// ํ
์คํธ ์ ๋ชฉํนํ msw ์๋ฒ์ ์ฐ๊ฒฐ
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
// ๊ฐ ํ
์คํธ ํ ๋ค๋ฅธ ํ
์คํธ์ ์ํฅ์ ๋ฏธ์น์ง ์๊ธฐ ์ํด ์ฐ๊ฒฐ๋ ํธ๋ค๋ฌ ์ด๊ธฐํ
afterEach(() => server.resetHandlers());
// ๋ชจ๋ ํ
์คํธ ์๋ฃ ํ ์ฐ๊ฒฐ ๋๊ธฐ
afterAll(() => server.close());ํ ์คํธ ํ๊ฒฝ์ธ jsdom์ Fetch API๊ฐ ์ ์ฉ๋์ง ์์๊ธฐ ๋๋ฌธ์ Fetch API๋ฅผ ์ฌ์ฉํ๋ ์ฝ๋๊ฐ ํ ์คํธ ๋์์ ํฌํจ๋๋ฉด ํ ์คํธ๋ฅผ ์คํจํ๋ค.
Fetch API์ ํด๋ฆฌํ์ธ whatwg-fetch ๋ฅผ ์ค์นํด ๋ชจ๋ ํ
์คํธ์ ์ ์ฉํ๋๋ก ์ค์ ํ์ผ์ import
Last updated