web

[React Test] 간단히 만들어보기 - ESLint Plugins, FireEvent 등

Jaaaay 2022. 8. 13. 14:20

ESLint Plugins 설치 및 설정

  • Plugins 란?

eslint에서 기본으로 제공하지 않는 다양한 규칙을 플러그인을 통해 사용할 수 있다.

  • 라이브러리 설치

npm install eslint-plugin-testing-library eslint-plugin-jest-dom --save-dev

  • .eslintrc.json 작성
{
  "plugins": ["testing-library", "jest-dom"],
  "extends": [
    "react-app",
    "react-app/jest",
    "plugin:testing-library/react",
    "plugin:jest-dom/recommended"
  ]
}

테스트 주도 개발(Test Driven Development)

  • Test Driven Development 란?

실제 코드를 작성하기 전에 코드를 먼저 작성한다.

테스트 코드를 작성한 후 그 테스트 코드를 Pass할 수 있는 실제 코드를 작성한다.

  • 장점
  1. TDD를 통해 많은 기능을 테스트하기에 소스 코드에 안정감 부여
  2. 실제 개발하면서 많은 시간이 소요되는 부분인 디버깅 과정을 TDD를 사용해 줄일 수 있어 개발 시간 절약
  3. 소스 코드를 더욱 신중하게 작성

카운터 숫자 구현해보기

// App.js
import "./App.css";
import { useState } from "react";

function App() {
  const [counter, setcounter] = useState(0);
  return (
    <div className="App">
      <header className="App-header">
        <h3 data-testid="counter">{counter}</h3>
      </header>
    </div>
  );
}

export default App;
// App.test.js
import { render, screen } from "@testing-library/react";
import App from "./App";

test("the counter starts at 0", () => {
  render(<App />);
  //screen object를 이용해서 원하는 엘리먼트에 접근(접근 시 ID로)
  const counterElement = screen.getByTestId("counter");
  // id가 counter인 엘리먼트의 텍스트가 0인지 테스트
  expect(counterElement).toHaveTextContent(0);
});


FireEvent API

유저가 발생시키는 액션(이벤트)에 대한 테스트를 해야하는 경우 사용

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

...

test("when the + button is pressed, the counter changes to 1", () => {
  render(<App />);
  const buttonElement = screen.getByTestId("plus-button");
  fireEvent.click(buttonElement);
  const counterElement = screen.getByTestId("counter");
  expect(counterElement).toHaveTextContent(1);
});
// App.js
...
<button
            data-testid="plus-button"
            onClick={() => setcounter((count) => count + 1)}
          >
            +
          </button>
...

on/off 버튼 만들기

  • toHaveStyle
test("on/off button has blue color", () => {
  render(<App />);
  const buttonElement = screen.getByTestId("on/off-button");
  expect(buttonElement).toHaveStyle({ backgroundColor: "blue" });
});
  • toBeDisabled
test("Prevent the -,+ button from being pressed when the on/off button is clicked", () => {
  render(<App />);
  const onOffButtonElement = screen.getByTestId("on/off-button");
  fireEvent.click(onOffButtonElement);
  const plusButtonElement = screen.getByTestId("plus-button");
  expect(plusButtonElement).toBeDisabled();
});
  • test.skip, test.only

특정 테스트를 스킵하거나, 그 테스트만 대상으로 진행할 수 있음