250x250
반응형
arkhyeon
arkhyeon
arkhyeon
전체 방문자
오늘
어제
  • 분류 전체보기 (88)
    • Spring (5)
    • Java (4)
    • React (25)
      • TypeScript (6)
      • JavaScript (1)
      • Jest (9)
    • NEXT (8)
    • SQL (1)
    • React native (1)
    • CSS (3)
    • Web (1)
    • Git (3)
    • ETC (6)
    • 빅데이터DB (8)
    • Docker (4)
    • Tool (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • websocket
  • javascript wss
  • react19
  • kudu
  • react
  • WSS
  • javasciprt websocket
  • jest
  • node WebSocket
  • react websocket
  • react spring websocket
  • react typescript
  • docker tomcat
  • Spring WebSocket
  • HIVE
  • react usetransition
  • react loading
  • usetransition
  • websocket server
  • react jest

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
arkhyeon

arkhyeon

React/Jest

Testing React with Jest and React Testing Library - 2

2023. 5. 31. 15:12
728x90
반응형

간단한 어플리케이션 테스트

import { fireEvent, render, screen } from "@testing-library/react";
import { logRoles } from "@testing-library/react";
import App from "./App";
import { replaceCamelWithSpaces } from "./App";

test("button has correct initial color and updates when clicked button", () => {
  const { container } = render(<App />);

  logRoles(container);

  // 이름이 'Change to blue'인 버튼 요소 찾기
  const colorButton = screen.getByRole("button", {
    name: "Change to MidnightBlue",
  });

  //배경색이 빨간색인지 확인
  expect(colorButton).toHaveStyle("background-color:MediumVioletRed");

  // 버튼 클릭
  fireEvent.click(colorButton);

  // 배경이 파란색으로 변경
  expect(colorButton).toHaveStyle("background-color:MidnightBlue");

  // 텍스트 변경 확인
  expect(colorButton).toHaveTextContent("Change to MediumVioletRed");
});

test("initial conditions", () => {
  render(<App />);
  // 버튼 활성화 상태로 시작
  const colorButton = screen.getByRole("button", {
    name: "Change to MidnightBlue",
  });
  expect(colorButton).toBeEnabled();
  // 체크박스가 체크되지 않은 상태로 시작

  const checkbox = screen.getByRole("checkbox");
  expect(checkbox).not.toBeChecked();
});

test("button turns disabled property when toggle checkbox", () => {
  render(<App />);

  const colorButton = screen.getByRole("button", {
    name: "Change to MidnightBlue",
  });
  const checkbox = screen.getByRole("checkbox", {
    name: "Change Disable Property",
  });
  // const checkbox = screen.getByLabelText('Change Disable Property')

  fireEvent.click(checkbox);
  expect(checkbox).toBeChecked();
  expect(colorButton).toBeDisabled();
  expect(colorButton).toHaveStyle("background-color:gray");

  fireEvent.click(checkbox);
  expect(checkbox).not.toBeChecked();
  expect(colorButton).toBeEnabled();
  expect(colorButton).not.toHaveStyle("background-color:gray");
});

describe("spaces before camel-case capital letters", () => {
  test("Works for no inner capital letters", () => {
    expect(replaceCamelWithSpaces("Red")).toBe("Red");
  });
  test("Works for one inner capital letter", () => {
    expect(replaceCamelWithSpaces("MidnightBlue")).toBe("Midnight Blue");
  });
  test("Works for multiple inner capital letters", () => {
    expect(replaceCamelWithSpaces("MediumVioletRed")).toBe("Medium Violet Red");
  });
});
  1. test(= it)
    • test(Test Name, expectations to test function, [timeout])
    • 테스트를 실행하는 메서드로 테스트 이름과 테스트할 함수를 작성할 수 있으며 중단하기 전에 대기하는 시간(Default : 5초)을 지정할 수 있습니다.
  2. logRoles
    • DOM 노드 트리 내의 ARIA 역할 목록을 콘솔에서 확인하여 getByRole() 로 Role 선택 시에 어떤 역할을 작성해야 하는지 알 수 있다.
    • Untitled.png
  3. getByRole
    • 접근 가능한 이름으로 반환된 요소를 조회할 수 있다.
      https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#roles
  4. expect
    • 👉 Custom Matchers List : https://github.com/testing-library/jest-dom
    • toHaveStyle(css: string | object)
      Untitled.png
      "@testing-library/jest-dom": "^5.16.5"
      //Object로 작성 시 모든 테스트가 통과되는 버그가 존재하기에 String으로 진행 권장 expect(colorButton).toHaveStyle({ backgroundColor: "anything" });//PASS
      expect(colorButton).toHaveStyle({ backgroundColor: "red" });//PASS
      expect(colorButton).toHaveStyle("background-color:red");//CHECK
      expect(colorButton).toHaveStyle(`background-color:anything`);//CHECK
    • toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean})
    • toBeEnabled() - 요소가 Enable 인지
    • toBeDisabled() - 요소가 Disable 인지
    • toBeChecked() - 요소가 Check 되었는지(해당 매쳐에는 반대가 없으므로 .not 사용) .not.toBeChecked()
  5. fireEvent
    • fireEvent.eventName(click, change...)(node: HTMLElement, eventProperties: Object)
    • 현재 상호작용을 위해 사용했지만 @testing-library/user-event 사용을 해야한다.
  6. describe
    • describe(name, fn) 여러 관련 테스트를 그룹화하여 테스트 진행
  7. toBe
    • toBe(value) 엄격한 동등 연산자

유닛 테스트 기준

  • 유닛 테스트 테스트 당 하나의 expect문 작성 권장
  • 기능 테스트 일련의 동작을 테스트
728x90
반응형

'React > Jest' 카테고리의 다른 글

Jest 원하는 테스트만 실행  (0) 2023.06.15
JEST Mock Service Worker 테스트 내부 사용  (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 - 1  (0) 2023.05.25
    'React/Jest' 카테고리의 다른 글
    • JEST Mock Service Worker 테스트 내부 사용
    • JEST Mock Service Worker 설정 및 기본 사용
    • React Jest user-event FireEvent
    • Testing React with Jest and React Testing Library - 1
    arkhyeon
    arkhyeon

    티스토리툴바