React - TestCode 2

Doodream·2021년 12월 9일
0

React

목록 보기
19/20
post-thumbnail

테스트 코드 파일 작성하기

Greeting.js

import { useState } from "react";

function Greeting() {
  const [changedText, setChangedText] = useState(false);
  const changeTextHandler = () => {
    setChangedText(true);
  };
  return (
    <div>
      <h2>Hello</h2>
      {changedText ? <p>바뀌었다!</p> : <p>만나서 반갑다!</p>}
      <button onClick={changeTextHandler}>Change Text!</button>
    </div>
  );
}

export { Greeting };

위 컴포넌트를 테스트 할 간단한 테스트 코드를 작성해봅시다.

테스트 주제는 아래와 같습니다.

  1. Hello 란 텍스트가 있는가?
  2. 버튼을 누르면 텍스트가 바뀌는가 ?

3A

여기서 우리는 3A 라는 개념으로 테스트 코드를 작성합니다.

Arrange

테스트 데이터와 조건들등 테스트 환경에 대한 배열입니다.

Act

테스트를 실행하는 로직입니다. 함수를 실행하는 형태입니다.

Assert

실행결과를 도달해야할 결과와 비교를 실행합니다.

Greeting.test.js

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Greeting } from "./Greeting";

describe("Greeting component", () => {
  test("renders : 안녕! : 해당 텍스트가 있는가", () => {
    // Arrange
    render(<Greeting />);

    //Act
    // ...nothing

    //Assert
    // 가상화면에서 해당 요소를 가지고 있는 Element를 반환합니다.
    const helloElement = screen.getByText("Hello", { exact: false });
    // Document에 이 요소가 있는지 확인합니다.
    expect(helloElement).toBeInTheDocument();
  });

  test("renders : 만나서 반갑다! : 버튼을 누르지 않았을 경우 해당 텍스트가 있는가", () => {
    render(<Greeting />);

    const outputElement = screen.getByText("만나서 반갑다!", { exact: false });
    expect(outputElement).toBeInTheDocument();
  });

  test("renders : 바뀌었다! : 버튼을 눌렀을 경우 해당 텍스트가 있는가?", () => {
    render(<Greeting />);

    //Act
    const buttonElement = screen.getByRole("button");
    userEvent.click(buttonElement);

    //Assert
    const outputElement = screen.getByText("바뀌었다!", { exact: false });
    expect(outputElement).toBeInTheDocument();
  });

  test("Not renders : 만나서 반갑다! : 버튼을 눌렀을 경우 해당 텍스트가 없는가", () => {
    render(<Greeting />);

    const buttonElement = screen.getByRole("button");
    userEvent.click(buttonElement);

    const outputElement = screen.queryByText("만나서 반갑다!", {
      exact: false,
    });
    expect(outputElement).toBeNull();
  });
});
  • describe : 테스트 코드를 그룹화 시켜서 묶습니다.
  • test : 테스트 케이스 하나를 작성합니다. it로 쓰기도 합니다.
  • screen : 가상으로 렌더링된 화면입니다.
  • .getByText : 가상으로 만들어진 화면에서 텍스트로 만들어진 요소가 있으면 반환하고 없으면 테스트를 실패합니다.
  • .getByRole : 가상으로 만들어진 화면에서 해당 태그로 만들어진 요소가 있으면 반환하고 없으면 실패합니다.
  • .queryByText : 가상으로 만들어진 화면에서 텍스트로 만들어진 요소가 있으면 반환하고 없으면 null 값을 반환합니다.
  • userEvent : 사용자가 이벤트를 발생시키는 것처럼 해당요소에 이벤트를 발생시킵니다.
  • expect : 해당요소와 결과 값을 비교합니다.
  • .toBeIntheDocument : 해당요소가 문서에 있는지 비교합니다.
  • .toBeNull : 해당요소가 null 값인지 확인합니다.
profile
일상을 기록하는 삶을 사는 개발자 ✒️ #front_end 💻

0개의 댓글