"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Ricks for React Testing Library를 위해 단위 테스트를 개선하기 위해

Ricks for React Testing Library를 위해 단위 테스트를 개선하기 위해

2025-02-07에 게시되었습니다
검색:191

ricks for React Testing Library to make your unit tests better

효과적인 반응 구성 요소 테스트가 중요합니다. RTL (React Testing Library) 은이 프로세스를 단순화하여 사용자 상호 작용 테스트를 강조합니다. 이 기사는보다 효율적이고 유지 관리 가능한 단위 테스트를 작성하기위한 5 가지 고급 RTL 기술을 제시합니다.


1. 쿼리 의 경우 화면

우선 순위를 지정합니다.

render () 에서 직접 파괴 쿼리를 피하십시오. 화면 객체를 사용하면 가독성과 선명도가 일관되게 향상됩니다.

이익:

  • 향상된 테스트 가독성.
  • 렌더링 된 화면 요소와의 상호 작용을 명시 적으로 보여줍니다.

예:

대신 :

const { getByText } = render();
expect(getByText(/click me/i)).toBeInTheDocument();

사용:

render();
expect(screen.getByText(/click me/i)).toBeInTheDocument();

이 접근법은 더 큰 테스트 스위트에서 일관성을 유지합니다.


2. 구성 요소 렌더링 요소의 경우 비동기 적으로 (예 : API 호출 후) findby 쿼리를 사용하여

getby

를 사용하십시오. 이것은 요소 렌더링 후에 만 ​​어설 션이 실행되도록합니다. 이익:

타이밍 문제로 인해 벗겨진 테스트를 제거합니다.

비동기 구성 요소에 대한보다 강력한 테스트를 만듭니다.
  • 예:

// 구성 요소를 비동기로 가져 와서 사용자 이름을 표시합니다 렌더 (); const username = screen.findbytext (/John Doe/i); 기대 (username) .tobeinthedocument ();

// Component asynchronously fetches and displays a username
render();
const userName = await screen.findByText(/john doe/i);
expect(userName).toBeInTheDocument();
findby

는 결합 된 getby 기능에 선호됩니다 기능 기능. 함께 사용하지 마십시오. render (); 대기 중 (() => { expling (screen.getByText (/john doe/i)). tobeintheDocument (); });

render();
await waitFor(() => {
  expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});
3.
내에서

내에서 정확한 타겟팅 특정 컨테이너 내에서 요소를 타겟팅 할 때

유틸리티의

는 모호한 일치를 방지합니다.

이익:

의도하지 않은 요소 선택을 방지합니다.
  • 테스트 정밀도를 향상시킵니다.
예:

세우다(
개인 정보 범례>
); const namelabel = 내 (screen.getByrole ( 'Group')). getByLabelText (/name/i); 기대 (namelabel) .tobeinthedocument ();
render(
  
Personal Information
); const nameLabel = within(screen.getByRole('group')).getByLabelText(/Name/i); expect(nameLabel).toBeInTheDocument();


4.

현실적인 상호 작용 fireevent

는 기능적이지만

userevent 는 타이핑, 클릭 및 탭 빙을 포함하여보다 현실적인 사용자 상호 작용 시뮬레이션을 제공합니다. 이익:

보다 정확한 이벤트 시뮬레이션.

    텍스트 입력과 같은 복잡한 상호 작용을 처리합니다.
  • 예:

'@testing-library/user-event'에서 userevent import userevent; 렌더 (); const emailinput = screen.getByLabelText (/email/i); const passwordinput = screen.getByLabelText (/password/i); const dopmentbutton = screen.getByRole ( 'button', {name : /submit /i}); userevent.type (emailinput, '[email protected]')를 기다립니다. userevent.type (passwordInput, 'password123')를 기다립니다. AWAIT userevent.click (제출부); excling (screen.getByText (/welcome/i)). TobeIntheDocument ();

import userEvent from '@testing-library/user-event';

render();
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /submit/i });

await userEvent.type(emailInput, '[email protected]');
await userEvent.type(passwordInput, 'password123');
await userEvent.click(submitButton);

expect(screen.getByText(/welcome/i)).toBeInTheDocument();

5.
dod vistrection

용 Debug () debug ()

메소드는 DOM 구조를 콘솔에 인쇄하여 테스트 실패 문제 해결에 매우 중요합니다.

이익:

누락 된 요소 또는 테스트 실패를 빠르게 식별합니다.

    디버깅을 단순화합니다.
  • 예:

render (); screen.debug (); // dom 구조를 기록합니다

render();
screen.debug(); // Logs the DOM structure

const 섹션 = screen.getByrole ( 'region'); 내 (섹션) .debug ();

render();
await waitFor(() => {
  expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});
추가 팁 :

사용자 상호 작용에 중점을 둡니다.
    내부 구성 요소 상태가 아닌 사용자가보고 상호 작용하는 것을 테스트하십시오.
  • 정리 : rtl이 클린 업을 처리하는 동안
  • cleanup ()
  • 이후에 가 Dom 누출을 방지합니다. 결론:
  • RTL은 사용자 중심 테스트를 우선시합니다. 이러한 기술을 적용하면 더 깨끗하고 신뢰할 수 있으며 유지 관리 가능한 테스트를 만들어 전반적인 개발 워크 플로를 향상시킵니다. 반응 테스트 관행을 향상시키기 위해 이러한 전략을 수용하십시오.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3