이번엔 React에서 적용해 보았다.
예제
프로젝트 생성
$ npx create-react-app tdd_test_react
$ cd tdd_test_react
My-Button.js
const MyButton = ({ onClick, disabled, children }) => (
<button type="button" onClick={onClick} disabled={disabled}>
{children}
</button>
);
export default MyButton;
간단한 Button 컴포넌트를 제작한다.
My-Button.test.js
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import MyButton from './My-Button';
describe('MY-Button', () => {
// Button 이 텍스트 콘텐츠를 렌더링하는지 테스트.
test('renders with text content', () => {
render(<MyButton>Click Me</MyButton>);
expect(screen.getByText('Click Me')).toBeInTheDocument();
});
// Button 클릭 시 onclick props 로 전달된 함수가 호출되는지 확인.
test('calls onClick function when clicked', () => {
const onClickMock = jest.fn();
render(<MyButton onClick={onClickMock}>Click Me</MyButton>);
const button = screen.getByRole('button');
fireEvent.click(button); // DOM 이벤트를 시뮬레이션할 때 사용하며, Button 컴포넌트에 등록된 onclick 이벤트가 호출되는지 확인한다.
expect(onClickMock).toHaveBeenCalled();
});
// Button이 Disabled props가 전달되었을 때 비활성화로 렌더링이 잘 되는지 확인
test('renders as disabled when disabled prop is passed', () => {
render(<MyButton disabled>Click Me</MyButton>);
const button = screen.getByRole('button');
expect(button).toBeDisabled();
});
});
실행 결과
$ npm run test
# 'react-scripts test'가 실행된다.