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에 의해 자동으로 채워집니다 ... */
});
반응형
'TIL' 카테고리의 다른 글
@RequestMapping&@PostMapping&@GetMapping 차이 (0) | 2022.05.24 |
---|---|
리눅스란? 우분투(Ubuntu)란? (0) | 2022.05.20 |
[JWT] JSON Web Token 이란? (0) | 2022.05.16 |
[Docker]도커란? 도커 기초 요약 정리 (0) | 2022.05.12 |
Redis 레디스 기본 개념 정리 (0) | 2022.05.09 |