728x90
반응형
https://arkhyeon.tistory.com/25
JEST Mock Service Worker 설정 및 기본 사용
Mock Service Worker Service Worker API를 사용하여 실제 요청을 가로채는 API Mocking 라이브러리입니다. 서버에 대한 호출을 막고 사용자가 작성한 응답을 전송 응답을 보내줄 핸들러 작성 핸들러를 이용해
arkhyeon.tistory.com
MSW 테스트 내용
기존의 성공한 핸들러를 서버 오류가 발생하도록 재정의하여 2개의 비동기 함수 오류 발생 시 알림창이 2개가 화면에 나오는지 테스트 진행
- 기존 설정된 MSW 핸들러
import { rest } from "msw";
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" },
])
);
}),
];
- 테스트 내부에서 사용할 핸들러
import { render, screen, waitFor } from "@testing-library/react";
import OrderEntry from "../OrderEntry";
import { rest } from "msw";
import { server } from "../../../mocks/server";
test("handles error for scoops and toppings routes", async () => {
//MSW 응답과 개별 테스트에 대한 응답을 오버라이딩한다.
server.resetHandlers(
rest.get("<http://localhost:3030/scoops>", (req, res, ctx) =>
//오류 테스트를 위한 오류 생성
res(ctx.status(500))
)
),
rest.get("<http://localhost:3030/toppings>", (req, res, ctx) =>
res(ctx.status(500))
);
render(<OrderEntry />);
//screen의 find 메서드는 항상 async await를 동반한다.
const alerts = await screen.findAllByRole("alert");
expect(alerts).toHaveLength(2);
});
server.resetHandlers()
초기 setupServer 호출 후 실행 중에 추가된 Request Handlers를 제거하고 재정의하여 사용
👍waitFor
위 테스트는 toHaveLength 단언문에서 1개만 찾을 수 있다는 오류가 발생하는데 screen.findAllByRole(”alert”) 에서 2개의 알림을 기다리지 않고 1개만 찾았을 때 단언문을 실행하여 오류가 발생하게된다.
이 때 waitFor을 사용하면 일정 시간 동안 기대치가 통과할 때 까지 기다릴 수 있다.
...
await waitFor(async () => {
const alerts = await screen.findAllByRole("alert");
expect(alerts).toHaveLength(2);
});
...
function waitFor<T>(
callback: () => T | Promise<T>,
options?: {
container?: HTMLElement
timeout?: number
interval?: number
onTimeout?: (error: Error) => Error
mutationObserverOptions?: MutationObserverInit
},
): Promise<T>
728x90
반응형
'React > Jest' 카테고리의 다른 글
JEST Custom Render (0) | 2023.06.16 |
---|---|
Jest 원하는 테스트만 실행 (0) | 2023.06.15 |
JEST Mock Service Worker 설정 및 기본 사용 (0) | 2023.06.15 |
React Jest user-event FireEvent (0) | 2023.06.07 |
Testing React with Jest and React Testing Library - 2 (0) | 2023.05.31 |