백엔드의 서비스를 모방하는 기술로, 실제 서버를 사용하지 않고 API 호출 프로세스를 모방한다.
// GET 함수 작성
const fetch = async () => {
const response = await axios.get("http://localhost:4000/users");
};
fetch();
// POST 요청 함수 작성
const handleAddUser = async () => {
const newUser: User = {
id: Date.now(),
name: `User${Date.now()}`,
};
await axios.post("http://localhost:4000/users", newUser);
setUsers((prev) => [ ...prev, newUser]);
}
장점
// Get 요청 함수
export const getUsers = async (): Promise<User[]> => {
const response = await axios.get<User[]>(
"https://jsonplaceholder.typicode.com/users"
);
const data = response.data;
return data;
}
// 테스트를 위한 Jest 코드를 작성
import axios from "axios";
import { getUsers } from "../src/user";
// axios 모킹
jest.mock("axios");
// 서버의 응답 데이터를 정의
const mockedUsers = [
{
id: 1,
name: "Leanne Graham",
username: "Leanne",
},
{
id: 2,
name: "Ervin Howell",
username: "Ervin",
},
];
test("should fetch users", async () => {
// 모킹된 axios.get()의 반환 값을 지정
const mockedResponse = { data: mockedUsers };
axios.get.mockResolvedValue(mockedResponse);
// get 요청 및 테스트
const users = await getUsers();
return expect(users).toBe(mockedUsers);
});
장점
단점
MSW 요청 플로우

// Get 요청 handler 작성
export const handlers = [
rest.get("https://jsonplaceholder.typicode.com/users", (req, res, ctx) => {
return res(ctx.delay(3000), ctx.status(200), ctx.json(user));
});
];
// 응답 모킹 데이터 작성
export const mockedUser: User[] = [
{
id: 1,
name: "모킹된 Leanne Graham",
username: "Leanne",
},
{
id: 2,
name: "모킹된 Ervin Howell",
username: "Ervin",
},
];
// Post 요청 handler 작성
rest.post(
"https://jsonplaceholder.typicode.com/users",
async (req, res, ctx) => {
const newMockedUser = await req.json<User>();
mockedUser.push(newMockedUser);
return res(ctx.status(201));
}
),
장점
단점
💡 OAS(Open API Specification) 란?
웹 서비스를 설명, 생성, 소비 및 시각화하기 위한 machine-readable한 인터페이스 정의 언어에 대한 사양
OAS의 특징
{
"todoList": [
{{# repeat (queryParam 'total' '20') }}
{
"id": {{ faker 'datatype.number' }},
"isDone": {{ faker 'datatype.boolean' }},
"title": {{ faker 'address.city' }}
},
{{/ repeat }}
]
}