TIL

[Jest] 리액트 테스트 코드 작성법

vluevy 2022. 5. 18. 15:43
728x90
반응형

리액트 테스트 코드

방법

  • 컴포넌트 트리 렌더링 : 간략화된 테스팅 환경 및 출력값이 확실한 경우
  • 완성된 앱에서의 테스트(엔드 투 엔드 테스트) : 현실적 브라우저 환경

보통 CRA(create react app)로 만든 리액트 앱에는 테스트 환경 준비 완료
App.test.js도 존재
터미널에 yarn test 입력해서 확인

  • describe : 어떤 기능을 하는지
  • it : 테스트 코드를 쪼갤 때 가장 작은 단위
  • expect : 특정값이 예상값과 일치하는지

describe > it > expect

jest프레임워크의 toMatchSnapshot / toMatchInlineSnapshot 를 사용하여 데이터 스냅샷 저장 가능

import renderer from 'react-test-renderer';
import Link from '../Link';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

컴포넌트를 작성하면

스냅샷파일은 이렇게 생성됨

exports[`renders correctly 1`] = `
<a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}
>
  Facebook
</a>
`; 

랜더링된 html을 pretty 패키지를 통해서 포맷 변환 가능

예시

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import pretty from "pretty";

import Hello from "./hello";

let container = null;
beforeEach(() => {
  // 렌더링 대상으로 DOM 엘리먼트를 설정합니다.
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // 기존의 테스트 환경을 정리합니다.
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

it("should render a greeting", () => {
  act(() => {
    render(<Hello />, container);
  });

  expect(
    pretty(container.innerHTML)
  ).toMatchInlineSnapshot(); /* ... jest에 의해 자동으로 채워집니다 ... */

  act(() => {
    render(<Hello name="Jenny" />, container);
  });

  expect(
    pretty(container.innerHTML)
  ).toMatchInlineSnapshot(); /* ... jest에 의해 자동으로 채워집니다 ... */

  act(() => {
    render(<Hello name="Margaret" />, container);
  });

  expect(
    pretty(container.innerHTML)
  ).toMatchInlineSnapshot(); /* ... jest에 의해 자동으로 채워집니다 ... */
}); 

https://jestjs.io/docs/api/

반응형