react unit 테스트 셋업

김주빈·2021년 12월 11일
0

unit-test

목록 보기
1/2
post-thumbnail

Jest 와 Enzyme 를 이용한 react(next) 테스트

테스트 코드를 작성하게 된 계기

QMIT 에 입사하여 plco 와 플코 for coach 를 만든지 1년이 지낫다.
그사이에 많은 일들이 있었다. 일하는 방식도 워터폴 에서 에자일로 바뀌었으며, 개발팀도 3명에서 6명으로 증가하였다. 팀원이 많아지고 개발속도가 증가하면서 기술 부채도 증가하기 시작했다. 이에 테스트 코드를 작성하여, 새롭게 추가된 코드, 수정된 코드가 기존의 policy를 침해하지 않았으면 하는 바램이 생겼다.

파일 구조

src
ㄴ tests
  ㄴ \_\_mock\_\_
  ㄴ \_\_storybook\_\_
  ㄴ \_\_tests\_\_
  ㄴ models (dummy 데이터들을 모아두었다)

셋업

  1. install packages
// for testing
jest enzyme wojtekmaj/enzyme-adapter-react-17
// for typescript
@types/enzyme @types/jest ts-jest 
  1. config 작성
  • jest config
// jest.config.js
module.exports = {
  setupFilesAfterEnv: ["<rootDir>/test.setup.ts"],
  testPathIgnorePatterns: ["<rootDir>/.next/", "/node_modules/", "<rootDir>/../../node_modules/"],
  preset: "ts-jest",
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  snapshotSerializers: ["enzyme-to-json/serializer"],
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.jest.json"
    }
  },
  moduleNameMapper: {
    "@common/(.*)": "<rootDir>/../common/src/$1",
    "@plco-pro/(.*)": "<rootDir>/src/$1",
    "@plco-pro-config/(.*)": "<rootDir>/config/$1",
    "\\.(css|less)$": "identity-obj-proxy"
  },
  timers: "fake",
  testEnvironment: "jsdom"
};
  • test setup
// test.setup.ts
import Adapter from "@wojtekmaj/enzyme-adapter-react-17";
import { configure } from "enzyme";

configure({ adapter: new Adapter() });

첫 테스트 코드

// plco-pro/src/tests/__tests__/atoms/button.test.tsx

import React from "react";

import { jest } from "@jest/globals";
import { mount } from "enzyme";

import { Button } from "@plco-pro/components/atoms/button";

it("it should perform the passed onClick function", () => {
  const mockClick = jest.fn();
  const wrapper = mount(
    <Button onClick={mockClick}>{"Button"}</Button>
  );
  wrapper.find("button").simulate("click");
  expect(mockClick).toBeCalledTimes(1);
});

it("it should not perform the passed onClick function when disabled true", () => {
  const mockClick = jest.fn();
  const wrapper = mount(
    <Button disabled onClick={mockClick}>{"Button"}</Button>
  );
  wrapper.find("button").simulate("click");
  expect(mockClick).toBeCalledTimes(0);
});

생각해 봐야할 것

  1. unit 테스트로 진행해야만 하는것.
  2. storybook 과 같은 UI 테스트로 진행 해야하는것.
  3. coverage 는 중요 하지 않다고 하는데, 최소한 몇 퍼센트까지는 유지를 해야하는지?
  4. TDD
profile
프론트엔드 개발자 김 주빈 입니다.

0개의 댓글