
describe나 it 같은 함수를 못 찾아서 빨간 줄이 뜰 수 있습니다.
이럴 때는 npm i --save-dev @types/jestscreen.debug()를 넣으면, 그 시점의 HTML 구조를 콘솔에 출력해 줍니다.// ... import 생략
describe('Counter 컴포넌트 동작 테스트', () => {
test('...', async () => {
const user = userEvent.setup();
render(<Counter />);
// [팁] 클릭하기 전 화면 상태 출력
console.log('--- 클릭 전 ---');
screen.debug();
const incrementBtn = screen.getByRole('button', { name: '+' });
await user.click(incrementBtn);
// [팁] 클릭한 후 화면 상태 출력
console.log('--- 클릭 후 ---');
screen.debug();
expect(screen.getByText('현재 숫자: 1')).toBeInTheDocument();
});
});button 태그가 CountButton)로 분리해 보겠습니다.
이때 중요한 것은 onClick 함수와 label(버튼 이름)을 받아오도록 설계합니다.// Props 타입을 정의하여 TypeScript의 장점을 살립니다.
interface Props {
label: string;
onClick: () => void;
}
export default function CountButton({ label, onClick }: Props) {
return (
<button type="button" onClick={onClick}>
{label}
</button>
);
}button 태그를 지우고, 방금 만든 import { useState } from 'react';
import CountButton from './CountButton'; // [추가]
export default function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(prev => prev + 1);
};
return (
<div>
<p>현재 숫자: {count}</p>
{/* [변경] 기존 button 태그 대신 컴포넌트 사용 */}
<CountButton label="+" onClick={handleClick} />
</div>
);
}npm test
PASS src/components/Counter.test.tsxgetByRole('button', { name: '+' })<button>+</button> (찾을 수 있음)<CountButton label="+" ... /> -> 결국 HTML로는 <button>+</button> (찾을 수 있음)git clone https://github.com/PROMLEE/my-tdd-app.git
cd my-tdd-app
git checkout part5@types/jest로 빨간 줄을 없애고, screen.debug()로 HTML 구조를 눈으로 확인했습니다.다음 시간에는6편. 상태(State) 변화 테스트를 통해 조건부 렌더링을 테스트하는 방법을 알아보겠습니다.