React Testing Library

speciaLLunch·2023년 4월 10일
0

TestDrivenDevelopment

목록 보기
3/5

Jest 프레임워크 적용에 뒤이어 RTL 라이브러리도 사용하여 테스트 환경 구축을 하였다. 기본적인 설정 및 자주 쓰이는 API에 대해 알아봤다.


React Testing Library

Mock API 테스트

Mock data란 실제 API에서 받아온 데이터가 아닌 필요에 의해 샘플로 만들어진 데이터

MSW

Mock Service Worker. 서비스 워커를 사용하여 네트워크 호출을 가로채는 API Mocking 라이브러리.

초기설정

  • handler
// src/mocks/handlers.js
import { rest } from 'msw'
import { API_SERVER } from '@api/server'

// Matches any "GET /user" requests,
// and responds using the `responseResolver` function.
export const handlers = [
rest.get`${API_SERVER}/user`, (req, res, ctx) => {
    return res(ctx.status(200), ctx.json(todos));
  }),
];
  • worker
// src/mocks/worker.js
import { setupWorker } from "msw";
import { handlers } from "./handlers";

export const worker = setupWorker(...handlers);
  • server
// src/mocks/server.js
import { setupServer } from "msw/node";
import { handlers } from "./handlers";

export const server = setupServer(...handlers);

-------------------------------------------------
// src/mocks/setupTests.js
import "@testing-library/jest-dom";
import { server } from "./mocks/server";

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

CORE API

Quries

Queries are the methods that Testing Library gives you to find elements on the page

  • 종류 : get, find, query

    • findBy는 비동기 Promise 반환 (default timeout 1000ms)

    • i.e. await screen.findByText('text', queryOptions, waitForOptions)

    • getByRole options

      getByRole(
        // If you're using `screen`, then skip the container argument:
        container: HTMLElement,
        role: string,
        options?: {
          hidden?: boolean = false,
          name?: TextMatch,
          description?: TextMatch,
          selected?: boolean,
          busy?: boolean,
          checked?: boolean,
          pressed?: boolean,
          suggest?: boolean,
          current?: boolean | string,
          expanded?: boolean,
          queryFallbacks?: boolean,
          level?: number,
          value?: {
            min?: number,
            max?: number,
            now?: number,
            text?: TextMatch,
          }
        }): HTMLElement
  • 우선순위
    1. getByRole
    2. getByLabelText
    3. getByPlaceholderText
    4. getByText
    5. getByDisplayValue
    6. getByAltText
    7. getByTitle
    8. getByTestId

https://www.youtube.com/playlist?list=PLZKTXPmaJk8JNJKFt7CK0jQvFIytGdf9n
https://www.daleseo.com/mock-service-worker/
https://mswjs.io/docs

profile
web front

0개의 댓글