본문 바로가기
WIKI 기술 지식 베이스

ADR007: http 요청을 모킹하기 위해 MSW 사용하기

원문 보기 위키 갱신

네트워크 요청 모킹은 모든 종류의 테스트에서 때로 정말 골칫거리가 될 수 있습니다.

출처: 문서

본문

맥락

네트워크 요청 모킹은 단위 테스트부터 e2e 테스트까지 모든 종류의 테스트에서 때로 정말 골칫거리가 될 수 있으며, 항상 각 테스트가 이러한 요청을 모킹하는 자체 구현을 가지고 있습니다. 외부 커뮤니티에서는 express 스타일의 경로 선언을 사용해 네트워크 요청을 모킹하는 이 라이브러리를 사용하는 흐름이 있었습니다. react-testing-library는 브라우저든 node든 상관없이 fetch를 직접 모킹하는 대신 이 라이브러리를 사용할 것을 권장합니다.

https://github.com/mswjs/msw

결정

앞으로 어떤 fetch 또는 XMLHTTPRequest가 발생하든 msw를 사용해 모킹하기로 결정했습니다.

예시는 다음과 같습니다.

import { http, HttpResponse } from 'msw';import { setupWorker } from 'msw/browser';const worker = setupWorker(  http.get('*/user/:userId', () => {    return HttpResponse.json({      firstName: 'John',      lastName: 'Maverick',    });  }),);// Start the Mock Service Workerworker.start();

그리고 더 실제적인 시나리오는 CatalogClient.test.ts에서 가져온 것입니다.

beforeEach(() => {  server.use(    http.get(`${mockApiOrigin}${mockBasePath}/entities`, () => {      return HttpResponse.json(defaultResponse);    }),  );});it('should entities from correct endpoint', async () => {  const entities = await client.getEntities();  expect(entities).toEqual(defaultResponse);});

결과

  • 작성할 코드가 조금 더 늘어납니다.

  • 점진적으로 코드베이스를 msw로 교체할 것입니다.

더 알아보기 (Learn more)