Frontend

Jest 및 테스팅 라이브러리로 React 테스트하기

단점이없어지고싶은개발자 2023. 1. 9. 20:34
반응형

이번 2023년 신년맞이 jest-testing-library를 활용해 React 테스트 하는 강의를 구입해서 들으면서, 테스트하는 부분을 조금 더 깊게 정리하고자 블로그 글을 작성한다.

https://www.udemy.com/course/jest-testing-library/

 


1. 테스트 종류

 

unit 테스트 : 코드의 한 유닛 혹은 단위별로 테스트
통합테스트 : 여러 유닛 간의 상호작용을 테스트
기능 테스트 : 기능테스트, 동작과 관련 테스트, 예시) 데이터 폼에 입력후 제출을 하면 바르게 동작하는지 확인하는 여부
end-to-end테스트 : 실제 브라우저가 필요하고, 앱이 연결된 서버가 필요, cypress가 대표적 도구

유닛테스트 vs 기능테스트

 
유닛 테스트

1. 테스트가 실패하면 정확히 어디서 발생하는지 알 수 있다.
2. 리팩토링으로 실패할 가능성이 있다.

기능 테스트

1. 테스트하는 특정 동작이나 유저 플로우와 관련된 모든 부분 포함, 테스트 통과하면 사용자의 문제제기가 없고, 견고하다는 의미
2. 디버깅이 어렵다는 단점이 존재. 어떤 부분 코드가 실패하는지 원인을 쉽게 찾을 수 없다.
예시테스트

 

아래에는 간단한 React 버튼을 만든 컴포넌트다
import { useState } from "react";
import "./App.css";

export function replaceCamelWithSpace(colorName) {
  return colorName.replace(/\B([A-Z])\B/g, " $1");
}

function App() {
  const [buttonColor, setButtonColor] = useState("red");
  const [disabled, setDisabled] = useState(false);
  const newButtonColor = buttonColor === "red" ? "blue" : "red";

  function clickedButtonHandler() {
    setButtonColor(newButtonColor);
  }

  function clickedCheckBoxHandler(e) {
    setDisabled(e.target.checked);
  }

  return (
    <div>
      <button
        disabled={disabled}
        onClick={clickedButtonHandler}
        style={{ backgroundColor: disabled ? "gray" : buttonColor }}
      >
        Change to {newButtonColor}
      </button>
      <input
        type="checkbox"
        onChange={clickedCheckBoxHandler}
        defaultChecked={disabled}
        id="disable-button-checkbox"
      />
      <label htmlFor="disable-button-checkbox">Disable button</label>
    </div>
  );
}

export default App;

 

유닛테스트를 먼저 볼텐데, 한 줄씩 뜯어보자

import { render, screen, fireEvent } from "@testing-library/react";
// testing-library에 있는 요소를 가지고 오는데
// render = 현재 해당 컴포넌트를 여는 것
// screen = 열려 있는 컴포넌트 안에 요소를 찾게 해주는 이벤트
// fireEvent = 유저가 할 수 있는 이벤트를 추가해주는 이벤튼

import App from "./App";

test("button has correct initial color, and update button", () => {
//test("어떤테스트인지", () => { 테스트 유무 });

  render(<App />); 
  //App 컴포넌트를 render 한다.

  const button = screen.getByRole("button", { name: "Change to blue" });
  //화면 버튼이라는 요소를 찾는데, name은 Change to blue이다.

  expect(button).toHaveStyle(`background-color: red`);
  // 예상된 테스트를 적어준다. button에 style의 배경은 빨간색 일 것이다.

  fireEvent.click(button);
  // 버튼을 클릭한다.

  expect(button).toHaveStyle("background-color: blue");
  // 예상된 테스트는 버튼의 색깔이 파랑색 일 것이다.
  expect(button).toHaveTextContent("Change to red");
  // 예상된 버튼의 textContent는 Change to red 일 것이다.
});

이런식으로 테스트를 작성할 수 있다.

 

추가적으로 testing-library에서는 fireEvent대신, userEvent를 사용을 권고하고 있다. 크게 차이는 없지만, 가장 큰 차이는 userEvent는 promise를 반환하기 때문에 사용할 때 비동기로 사용을 해야한다. 

 

("test", async () => {
	...
	await user.click(button);
    ...
});

 

https://testing-library.com/docs/dom-testing-library/api-events/

 

Firing Events | Testing Library

Note

testing-library.com

 

 


- 아래 페이지는 testing-library에서 DOM요소를 활용할 때 유용할 게 쓸 수 있다.

https://github.com/testing-library/jest-dom#tobedisabled

 

GitHub - testing-library/jest-dom: Custom jest matchers to test the state of the DOM

:owl: Custom jest matchers to test the state of the DOM - GitHub - testing-library/jest-dom: Custom jest matchers to test the state of the DOM

github.com

 

- 아래 페이지는 어떤 요소를 테스트할 때, 해당 요소에 대한 명칭을 찾을 수 있다.

https://www.w3.org/TR/wai-aria/#role_definitions

 

Accessible Rich Internet Applications (WAI-ARIA) 1.1

A section of a page that consists of a composition that forms an independent part of a document, page, or site. An article is not a navigational landmark, but may be nested to form a discussion where assistive technologies could pay attention to article ne

www.w3.org

 

- 아래 페이지는 testing-library에 사이트다.

https://testing-library.com/

 

Testing Library | Testing Library

Simple and complete testing utilities that encourage good testing practices

testing-library.com

 

반응형

'Frontend' 카테고리의 다른 글

How does the Internet Work?  (0) 2023.09.02
프론트엔드 성능 최적화 - (Litghthouse 사용법)  (0) 2023.03.12
copy-on-write 및 방어적 복사  (0) 2022.12.18
프로그래머스 > 예상 대진표  (0) 2022.10.29
SWR이란?  (0) 2022.08.19