Testing Library 완벽 가이드 | React·Vue·사용자 중심 테스트·실전 활용
이 글의 핵심
Testing Library 완벽 가이드에 대해 정리한 개발 블로그 글입니다. Testing Library로 사용자 중심 테스트를 구현하는 완벽 가이드입니다. Queries, User Events, Async Utils, React/Vue 통합까지 실전 예제로 정리했습니다. > 실무 경험 공유:… 개념과 예제 코드를 단계적으로 다루며, 실무·학습에 참고할 수 있도록 구성했습니다. 관련…
이 글의 핵심
Testing Library로 사용자 중심 테스트를 구현하는 완벽 가이드입니다. Queries, User Events, Async Utils, React/Vue 통합까지 실전 예제로 정리했습니다.
실무 경험 공유: Enzyme에서 Testing Library로 전환하면서, 테스트가 더 견고해지고 리팩토링이 안전해진 경험을 공유합니다.
들어가며: “테스트가 구현에 의존해요”
실무 문제 시나리오
시나리오 1: 리팩토링 시 테스트가 깨져요
구현 세부사항을 테스트합니다. Testing Library는 사용자 관점으로 테스트합니다. 시나리오 2: 테스트가 실제 사용과 달라요
내부 state를 직접 확인합니다. Testing Library는 렌더링 결과를 확인합니다. 시나리오 3: 접근성을 고려하지 못해요
ID, className으로 선택합니다. Testing Library는 Role, Label로 선택합니다.
1. Testing Library란?
핵심 특징
Testing Library는 사용자 중심 테스팅 라이브러리입니다. 주요 장점:
- 사용자 중심: 구현이 아닌 동작 테스트
- 접근성: Role, Label 기반
- 견고함: 리팩토링에 안전
- 프레임워크 지원: React, Vue, Angular
- Jest/Vitest 통합: 완벽한 호환
2. 설치 및 설정
React
npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event
Vue
npm install -D @testing-library/vue
3. 기본 테스트 (React)
// src/components/Button.tsx
interface ButtonProps {
label: string;
onClick?: () => void;
}
export default function Button({ label, onClick }: ButtonProps) {
return <button onClick={onClick}>{label}</button>;
}
// src/components/Button.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import Button from './Button';
test('renders button', () => {
render(<Button label="Click me" />);
expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument();
});
test('handles click', async () => {
const user = userEvent.setup();
const handleClick = jest.fn();
render(<Button label="Click me" onClick={handleClick} />);
await user.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
4. Queries
우선순위
- getByRole: 접근성 기반 (권장)
- getByLabelText: Form 요소
- getByPlaceholderText: Placeholder
- getByText: 텍스트 내용
- getByDisplayValue: Input 값
- getByAltText: 이미지
- getByTitle: Title 속성
- getByTestId: data-testid (최후)
예제
// getByRole
screen.getByRole('button', { name: 'Submit' });
screen.getByRole('textbox', { name: 'Email' });
screen.getByRole('heading', { level: 1 });
// getByLabelText
screen.getByLabelText('Email');
// getByPlaceholderText
screen.getByPlaceholderText('Enter email');
// getByText
screen.getByText('Hello World');
screen.getByText(/hello/i);
// getByTestId
screen.getByTestId('custom-element');
5. Query Variants
// getBy: 즉시 찾음 (없으면 에러)
screen.getByRole('button');
// queryBy: 즉시 찾음 (없으면 null)
screen.queryByRole('button');
// findBy: 비동기 대기 (없으면 에러)
await screen.findByRole('button');
// getAllBy: 여러 개
screen.getAllByRole('listitem');
6. User Events
import userEvent from '@testing-library/user-event';
test('user interactions', async () => {
const user = userEvent.setup();
render(<LoginForm />);
// 타이핑
await user.type(screen.getByLabelText('Email'), '[email protected]');
// 클릭
await user.click(screen.getByRole('button', { name: 'Submit' }));
// 선택
await user.selectOptions(screen.getByLabelText('Country'), 'US');
// 체크박스
await user.click(screen.getByRole('checkbox', { name: 'Agree' }));
// 파일 업로드
const file = new File(['hello'], 'hello.png', { type: 'image/png' });
const input = screen.getByLabelText('Upload');
await user.upload(input, file);
});
7. 비동기 테스트
waitFor
import { render, screen, waitFor } from '@testing-library/react';
test('loads users', async () => {
render(<UserList />);
await waitFor(() => {
expect(screen.getByText('John')).toBeInTheDocument();
});
});
findBy
test('loads users', async () => {
render(<UserList />);
expect(await screen.findByText('John')).toBeInTheDocument();
});
8. Form 테스트
// src/components/LoginForm.tsx
export default function LoginForm({ onSubmit }: { onSubmit: (data: any) => void }) {
const [email, setEmail] = useState(');
const [password, setPassword] = useState(');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onSubmit({ email, password });
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<label htmlFor="password">Password</label>
<input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
}
// src/components/LoginForm.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginForm from './LoginForm';
test('submits form', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<LoginForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]');
await user.type(screen.getByLabelText('Password'), 'password123');
await user.click(screen.getByRole('button', { name: 'Submit' }));
expect(handleSubmit).toHaveBeenCalledWith({
email: '[email protected]',
password: 'password123',
});
});
9. Vue 통합
// src/components/Button.vue
<script setup lang="ts">
defineProps<{
label: string;
}>();
const emit = defineEmits<{
click: [];
}>();
</script>
<template>
<button @click="emit('click')">{{ label }}</button>
</template>
// src/components/Button.test.ts
import { render, screen } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';
import Button from './Button.vue';
test('renders button', () => {
render(Button, { props: { label: 'Click me' } });
expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument();
});
test('handles click', async () => {
const user = userEvent.setup();
const { emitted } = render(Button, { props: { label: 'Click me' } });
await user.click(screen.getByRole('button'));
expect(emitted().click).toHaveLength(1);
});
정리 및 체크리스트
핵심 요약
- Testing Library: 사용자 중심 테스팅
- Queries: Role, Label 기반
- User Events: 실제 사용자 시뮬레이션
- Async Utils: 비동기 대기
- 프레임워크 지원: React, Vue, Angular
- Jest/Vitest 통합: 완벽한 호환
구현 체크리스트
- Testing Library 설치
- 기본 테스트 작성
- Queries 활용
- User Events 사용
- 비동기 테스트
- Form 테스트
- Vue/React 통합
- CI/CD 통합
같이 보면 좋은 글
이 글에서 다루는 키워드
Testing Library, React, Vue, Testing, User-Centric, Jest, Vitest
자주 묻는 질문 (FAQ)
Q. Enzyme과 비교하면 어떤가요?
A. Testing Library가 더 사용자 중심적이고 견고합니다. Enzyme은 더 이상 활발히 개발되지 않습니다.
Q. E2E 테스트도 가능한가요?
A. 아니요, 단위/통합 테스트에 적합합니다. E2E는 Cypress나 Playwright를 사용하세요.
Q. 학습 곡선은 어떤가요?
A. 매우 낮습니다. 사용자 관점으로 생각하면 됩니다.
Q. 프로덕션에서 사용해도 되나요?
A. 네, React 공식 문서에서 권장하는 테스팅 라이브러리입니다.
심화 부록: 구현·운영 관점
이 부록은 앞선 본문에서 다룬 주제(「Testing Library 완벽 가이드 | React·Vue·사용자 중심 테스트·실전 활용」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.
내부 동작과 핵심 메커니즘
flowchart TD A[입력·요청·이벤트] --> B[파싱·검증·디코딩] B --> C[핵심 연산·상태 전이] C --> D[부작용: I/O·네트워크·동시성] D --> E[결과·관측·저장]
sequenceDiagram participant C as 클라이언트/호출자 participant B as 경계(런타임·게이트웨이·프로세스) participant D as 의존성(API·DB·큐·파일) C->>B: 요청/이벤트 B->>D: 조회·쓰기·RPC D-->>B: 지연·부분 실패·재시도 가능 B-->>C: 응답 또는 오류(코드·상관 ID)
- 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
- 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
- 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
- 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.
프로덕션 운영 패턴
| 영역 | 운영 관점 질문 |
|---|---|
| 관측성 | 요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가 |
| 안전성 | 입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가 |
| 신뢰성 | 재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가 |
| 성능 | 캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가 |
| 배포 | 롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가 |
| 용량 | 피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가 |
스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.
확장 예시: 엔드투엔드 미니 시나리오
앞선 본문 주제(「Testing Library 완벽 가이드 | React·Vue·사용자 중심 테스트·실전 활용」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.
- 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
- 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
- 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
- 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
- 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
ctx = newCorrelationId()
validated = validateSchema(request)
authorize(validated, ctx)
result = domainCore(validated)
persistOrEmit(result, idempotentKey)
recordMetrics(ctx, latency, outcome)
return result
문제 해결(Troubleshooting)
| 증상 | 가능 원인 | 조치 |
|---|---|---|
| 간헐적 실패 | 레이스, 타임아웃, 외부 의존성, DNS | 최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검 |
| 성능 저하 | N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스 | 프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거 |
| 메모리 증가 | 캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납 | 상한·TTL·힙/FD 스냅샷 비교 |
| 빌드·배포만 실패 | 환경 변수, 권한, 플랫폼 차이, lockfile | CI 로그와 로컬 diff, 런타임·이미지 버전 핀 |
| 설정 불일치 | 프로필·시크릿·기본값, 리전 | 스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화 |
| 데이터 불일치 | 비멱등 재시도, 부분 쓰기, 캐시 무효화 누락 | 멱등 키·아웃박스·트랜잭션 경계 재검토 |
권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.
배포 전에는 git add → git commit → git push 후 npm run deploy 순서를 권장합니다.