RTL,Jest - 1(컬러버튼)

hoin_lee·2023년 8월 6일
0

Jest

목록 보기
2/2

간단한 버튼 테스트 해보기

TDD 스타일대로 하려면 기능 코드를 추가하기 전에 테스트를 작성해야 한다
먼저 이전 0번 글에서 했던 App.js를 초기화 했다

function App() {
  return (
    <div />
  );
}
export default App;

이래야 테스트가 통과되니 빈 쉘로만들었다
이후 테스트 케이스를 작성했다

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

test("button has correct initial color", () => {
  render(<App />);
  // 파란색으로 변경 텍스트와 버튼이 있는지 여부
  const colorButton = screen.getByRole("button", { name: "Change to blue" });

  //배경색이 빨강으로 변하는지 예상
  expect(colorButton).toHaveStyle({ backgroundColor: "red" });
});

test("button turns blue when clicked", () => {});

현재는 App.js에 아무것도 안적었으니 당연히 에러가 생기고 버튼하나를 추가해보자

function App() {
  return (
    <div>
      <button style={{backgroundColor: 'red'}}>Change to blue</button>
    </div>
  );
}
export default App;

이러면 테스트는 통과 된다. 마지막 테스트에는 아무것도 실행시키지 않았으니 통과되는 게 맞다

Roles 디버깅을 위한 logRoles

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

test("button has correct initial color", () => {
  const {container} = render(<App />); // 구조분해 할당으로 container꺼내기
  logRoles(container)//logroles를 통해 콘솔창에서 요소 확인가능
  // 파란색으로 변경 텍스트와 버튼이 있는지 여부
  const colorButton = screen.getByRole("button", { name: "Change to blue" });

  //배경색이 빨강으로 변하는지 예상
  expect(colorButton).toHaveStyle({ backgroundColor: "red" });
});

test("button turns blue when clicked", () => {});

여기서 알아야 할 건 @testing-library/react에 속해있는 logRoles가 아니라 @testing-library/dom에 속해있는 logRoles라는 것이다
이렇게 입력하면

  console.log
    button:

    Name "Change to blue":
    <button
      style="background-color: red;"
    />

이렇게 콘솔이 출력되는 것을 확인할 수 있다

여기서 하나의 역할, 즉 이 버튼이 출력되고 버튼의 이름을 알 수 있다
페이지가 길어서 역할이 있는 항목들이 헷갈릴 경우엔 유용하게 사용할 수 있다

profile
https://mo-i-programmers.tistory.com/

0개의 댓글