[Jest] fireEvent VS userEvent
사용자 이벤트에 의한 DOM 변경에 대한 테스트가 필요할 때, 보통 fireEvent 나 userEvent 를 사용한다.
두 개의 특징과 사용법에 대한 차이점을 살펴보고, 적합한 방법에 대해 고민해보자.
https://testing-library.com/docs/dom-testing-library/api-events/ 에 의하면 userEvent 사용을 권장하고 있다.
Firing Events | Testing Library
Note
testing-library.com
아래는 https://testing-library.com/docs/user-event/intro의 전문을 부분해석한 내용입니다.
fireEvent는 DOM 이벤트를 전달하는 반면 user-event는 전체 상호 작용을 시뮬레이트하여 여러 이벤트를 실행하고 그 과정에서 추가 검사를 수행할 수 있습니다. user-event를 사용하면 구체적인 이벤트 대신 사용자 상호 작용을 설명할 수 있습니다. 그 과정에서 가시성 및 상호작용성 검사를 추가하고 브라우저의 사용자 상호작용과 마찬가지로 DOM을 조작합니다.
1. import 차이
// fireEvent
import { fireEvent } from "@testing-library/react";
//userEvent
import userEvent from "@testing-library/user-event";
2. 객체 생성
test("create userEvent instance", async () => {
// user 객체로부터 모든 userEvent 메소드를 사용할 수 있음.
const user = userEvent.setup();
});
3. async - await 기재 (@testing-library/user-event ver14 이후의 change log이지만, 14 이후 버전을 사용할 것을 권고하고 있습니다.)
userEvent 메소드는 Promise 를 반환하기 때문에 반드시 await 기재가 필요하다.
그렇지 않으면 userEvent 메소드(ex. click)가 일을 끝내기 전에 assertion(expext 문)이 실행되고, 에러가 발생하게 됨.
test("create userEvent instance", async () => {
// user 인스턴스로부터 모든 userEvent 메소드를 사용할 수 있음.
const user = userEvent.setup();
const colorButton = screen.getByRole("button", { name: "버튼입니다." });
await user.click(colorButton);
expect(colorButton).toHaveTextContent('버튼입니다.');
});