React Testing Library


개요

  • 리액트에서는 CRA를 하면 기본적으로 jest 세팅이 되어있다.
  • 어떠한 컴포넌트에서 특정 문자열을 랜더링하고 있는지를 테스트하는 코드는 다음과 같다.
  • // TestHeader.tsx
    import React from 'react';
    export default function TestHeader({ isLogin, userId }: { isLogin: boolean; userId?: string }) {
    return (
    <div>
    {isLogin ? (
    <h1>{userId}님 환영합니다!</h1>
    ) : (
    <h1>
    로그인 해주세요! <button>로그인</button>
    </h1>
    )}
    </div>
    );
    }
    // TestHeader.test.tsx
    import { render, screen } from '@testing-library/react';
    import TestHeader from './TestHeader';
    test('isLogin이 true로 전달이 된 상태에서, userId가 잘 뜨는지', () => {
    render(<TestHeader isLogin={true} userId='jke' />);
    const textEl = screen.getByText(/jke님 환영합니다!/);
    expect(textEl).toBeInTheDocument();
    });
    test('isLogin이 false일 때, 문구와 button이 정상 출력되는지 확인', () => {
    render(<TestHeader isLogin={false} />);
    const textEl = screen.getByText(/로그인 해주세요!/);
    const btnEl = screen.getByRole('button');
    screen.debug();
    expect(textEl).toBeInTheDocument();
    expect(btnEl).toBeInTheDocument();
    expect(btnEl).toHaveTextContent('로그인');
    });
  • 여기서 screen은 말 그대로 현재 렌더링이 진행되고 있는 화면을 의미한다.
  • screen.debug 는 테스트 과정에서 출력된 DOM을 확인하고 싶을 때 사용할 수 있다.
  • 요소를 가져오는 메소드들

  • getElementBy~ 나 querySelector와 같이 RTL에서도 렌더링된 요소들에게 접근할 수 있는 메소드들이 존재한다.
  • userEvent

  • 실제 DOM상에서의 유저처럼 이벤트를 발생시키기 위해서는 testing-library/user-event 라이브러리를 사용할 수 있다.
  • 아래처럼 userEvent.이벤트명(엘리먼트) 의 형태로 활용할 수 있다.
  • // TestCounter.tsx
    import React, { useState } from 'react';
    export default function TestCounter() {
    const [count, setCount] = useState(0);
    const onClickBtn = () => {
    setCount(cur => cur + 1);
    };
    return <button onClick={onClickBtn}>현재 숫자: {count}</button>;
    }
    // TestCounter.test.tsx
    import { render, screen } from '@testing-library/react';
    import userEvent from '@testing-library/user-event';
    import '@testing-library/jest-dom';
    import TestCounter from './TestCounter';
    test('버튼의 온클릭 함수 작동하는지', () => {
    render(<TestCounter />);
    const btn = screen.getByRole('button');
    expect(btn).toHaveTextContent('현재 숫자: 0');
    userEvent.click(btn);
    expect(btn).toHaveTextContent('현재 숫자: 1');
    });
  • 이렇게 하면 click 이벤트가 발생하고 아래 테스트가 통과한다.