이번 2023년 신년맞이 jest-testing-library를 활용해 React 테스트 하는 강의를 구입해서 들으면서, 테스트하는 부분을 조금 더 깊게 정리하고자 블로그 글을 작성한다.
https://www.udemy.com/course/jest-testing-library/
1. 테스트 종류
유닛테스트 vs 기능테스트
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에 사이트다.
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 |