CRA 환경이라고 가정한다.
설치
$ yarn add @testing-library/react
$ yarn add @testing-library/jest-dom
CRA내부적으로 jest 가 설치되어있기 때문에 redundant하다고 error를 내긴 하던데..
React Testing Library 설정
import "@testing-library/jest-dom/extend-expect";
jest-dom 이 제공하는 matcher를 Jest 테스트 러너에게 인식시키는 것입니다.
import "@react-testing-library/cleanup-after-each";
이거를 포함하라는 글이 많은데, error를 낸다. 그냥 @testing-library/react 의 cleanup 사용.
// loginForm.test.jsx
import { render, fireEvent, cleanup } from "@testing-library/react";
import LoginForm from "./loginForm";
afterEach(cleanup);
describe("<LoginForm />", () => {
it("이메일과 패스워드가 모두 입력되었다면 버튼이 활성화 됩니다.", () => {
const { getByText, getByLabelText } = render(
<LoginForm onSubmit={() => null} />
);
const button = getByText("로그인");
const email = getByLabelText("이메일");
const password = getByLabelText("비밀번호");
expect(button).toBeDisabled();
fireEvent.change(email, { target: { value: "[email protected]" } });
fireEvent.change(password, { target: { value: "malzaPass" } });
expect(button).toBeEnabled();
});
});