728x90
Jest 설치가 안되어있다면 아래 게시물을 보고 오시길 추천드립니다
Jest import 방법 (With @ 포함 경로 인식) (tistory.com)
테스트용 컴포넌트
// MyComponent.tsx
import React from 'react';
// Props 타입 정의
interface Props {
title: string;
onClick: () => void;
}
// React.FC를 사용하지 않는 MyComponent 함수형 컴포넌트
export const MyComponent = ({ title, onClick }: Props) => {
return (
<div>
{/* title prop으로 전달받은 값을 h1 요소에 표시 */}
<h1>{title}</h1>
{/* onClick prop으로 전달받은 함수를 버튼의 onClick 이벤트 핸들러로 설정 */}
<button onClick={onClick}>Click me</button>
</div>
);
};
export default Mycomponent
테스트 코드
// MyComponent.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { MyComponent } from './MyComponent';
// MyComponent 테스트 그룹
describe('MyComponent', () => {
// 제목 렌더링 테스트
it('renders the title correctly', () => {
// MyComponent를 렌더링하고, 가상 DOM에 삽입
render(<MyComponent title="Test title" onClick={() => {}} />);
// Test title이라는 텍스트를 가진 요소를 찾아서 titleElement 변수에 저장
const titleElement = screen.getByText(/Test title/i);
// titleElement가 문서에 존재하는지 확인
expect(titleElement).toBeInTheDocument();
});
// 버튼 클릭 이벤트 테스트
it('calls onClick when button is clicked', () => {
// onClick 이벤트 핸들러 모의 함수 생성
const onClickMock = jest.fn();
// MyComponent를 렌더링하고, 가상 DOM에 삽입
render(<MyComponent title="Test title" onClick={onClickMock} />);
// Click me라는 텍스트를 가진 버튼 요소를 찾아서 buttonElement 변수에 저장
const buttonElement = screen.getByText(/Click me/i);
// buttonElement를 클릭
fireEvent.click(buttonElement);
// onClickMock 함수가 정확히 한 번 호출되었는지 확인
expect(onClickMock).toHaveBeenCalledTimes(1);
});
});
728x90
'JavaScript' 카테고리의 다른 글
Jest & testing-library/react로 React Test 코드 구성하기 -1 [render(), screen 배워보기] (0) | 2023.04.21 |
---|---|
Jest vscode Snippet 만들기 (0) | 2023.04.21 |
Jest import 방법 (With @ 포함 경로 인식) (0) | 2023.04.20 |
JS DeepCopy [feat : 변경한 적 없는 객체 값 변경됨 해결] (0) | 2023.04.14 |
The left-hand side of an assignment expression may not be an optional property access 오류 해결 (0) | 2023.04.12 |
댓글