
src/utils/calculator.ts를 만들고 테스트해 봅시다.export const add = (a: number, b: number) => a + b;
export const formatPrice = (price: number) => `${price.toLocaleString()}원`;import { describe, it, expect } from 'vitest';
import { add, formatPrice } from './calculator';
describe('계산기 유틸리티 단위 테스트', () => {
it('두 숫자를 더한다', () => {
const result = add(1, 2);
console.log(`[Unit] add(1, 2) 결과: ${result}`);
expect(result).toBe(3);
});
it('숫자를 금액 포맷으로 변환한다', () => {
const result = formatPrice(10000);
console.log(`[Unit] formatPrice(10000) 결과: ${result}`);
expect(result).toBe('10,000원');
});
});npm test calculator
[Unit] add(1, 2) 결과: 3
[Unit] formatPrice(10000) 결과: 10,000원
PASS src/utils/calculator.test.tsLoginForm은 입력창(Input), 버튼(Button), 상태(State), 검증 로직(Validation)이 모두 합쳐져 있습니다.
이것이 바로 통합 테스트입니다.import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { vi, describe, test, expect } from 'vitest';
import LoginForm from './LoginForm';
describe('로그인 폼 통합 테스트', () => {
test('사용자가 이메일을 입력하고 로그인 버튼을 누르는 전체 흐름', async () => {
const user = userEvent.setup();
const handleSubmit = vi.fn();
render(<LoginForm onSubmit={handleSubmit} />);
// [통합] 여러 요소(Input, Button)가 상호작용합니다.
const emailInput = screen.getByLabelText('이메일');
const passwordInput = screen.getByLabelText('비밀번호');
const submitBtn = screen.getByRole('button', { name: '로그인' });
console.log('[Integration] 사용자 입력 시뮬레이션');
await user.type(emailInput, 'user@test.com');
await user.type(passwordInput, '1234');
console.log('[Integration] 버튼 클릭');
await user.click(submitBtn);
// 검증 로직과 상태 관리가 잘 통합되어 작동했는지 확인
expect(handleSubmit).toHaveBeenCalledWith({
email: 'user@test.com',
password: '1234'
});
});
});npm test integration
[Integration] 사용자 입력 시뮬레이션
[Integration] 버튼 클릭
PASS src/components/LoginForm.integration.test.tsxadd(1, 2) 같은 순수 함수 로직 검증에 집중하세요.render(<Component />)를 통해 사용자가 버튼을 누르고 화면이 바뀌는 것을 검증하세요. git clone https://github.com/PROMLEE/my-tdd-app.git
cd my-tdd-app
git checkout part13다음 시간에는14편. 실무에서의 React TDD 적용 시 고려사항을 통해, 팀 프로젝트에서 TDD를 도입할 때 부딪히는 현실적인 문제와 해결책을 이야기해 보겠습니다.