[react] 생명주기 메서드를 사용하여 테스트 코드를 작성하는 방법은 무엇인가요?

다음은 생명주기 메서드를 사용하여 테스트 코드를 작성하는 간단한 예제입니다.

import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

// componentDidMount 메서드를 테스트하는 예제
test('componentDidMount 테스트', () => {
  render(<MyComponent />);
  // componentDidMount에서 특정 데이터가 로드되었는지 확인하는 코드
  expect(screen.getByText(/로드된 데이터/)).toBeInTheDocument();
});

// componentDidUpdate 메서드를 테스트하는 예제
test('componentDidUpdate 테스트', () => {
  const newData = { /* 새로운 데이터 객체 */ };
  const { rerender } = render(<MyComponent data={oldData} />);
  rerender(<MyComponent data={newData} />);
  // componentDidUpdate에서 UI가 업데이트되었는지 확인하는 코드
  expect(screen.getByText(/새로운 데이터가 반영된 UI/)).toBeInTheDocument();
});

이 예제에서는 @testing-library/react를 사용하여 테스트를 작성하였으며, componentDidMountcomponentDidUpdate 메서드를 테스트하는 방법을 보여주었습니다.

참고문헌: