[CRA+JS+Jest] 테스트 환경 만들기

BOKS·2023년 1월 18일
0

* TS로 하지 않았습니다. 참고 바랍니다.


1. CRA로 리액트 앱 만들기

react 공식 홈페이지 참고

https://create-react-app.dev/docs/getting-started/

공식 홈페이지를 참고하여 각자의 CRA 프로젝트를 만듭니다.

yarn create react-app ${APPNAME}

2. JEST 설정하기

jest 공식 홈페이지 참고

https://jestjs.io/docs/tutorial-react

yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer
  1. 위 명령어를 실행하여 jest를 설치하면서 react 테스트를 위한 package까지 받아온다 (공식 홈페이지 참고)
module.exports = {
    presets: [
        "@babel/preset-env", ["@babel/preset-react", {"runtime": "automatic"}]
      ]
}
  1. jest를 react 환경에서 실행하기 위해 babel 설정을 해줘야 한다.
    특히 runtime automatic 값이 없다면 추가해줘야 테스트가 정상적으로 동작한다. (공식 홈페이지에도 작성되어 있다.)

3. 테스트 해보기

먼저 테스트 전에 자동으로 추가 되어있는 App.test.js를 삭제한다.
두 번째로 package.json 내 scripts 중 test를 변경한다. (꼭 하지 않아도 된다.)

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "yarn jest", << 이 부분 변경
    "eject": "react-scripts eject"
  },

테스트할 데이터는 공식 홈페이지에 있는 코드로 진행한다.

// src/Link.js
import {useState} from 'react';

const STATUS = {
  HOVERED: 'hovered',
  NORMAL: 'normal',
};

export default function Link({page, children}) {
  const [status, setStatus] = useState(STATUS.NORMAL);

  const onMouseEnter = () => {
    setStatus(STATUS.HOVERED);
  };

  const onMouseLeave = () => {
    setStatus(STATUS.NORMAL);
  };

  return (
    <a
      className={status}
      href={page || '#'}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    >
      {children}
    </a>
  );
}
// src/Link.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import Link from './Link';

it('changes the class when hovered', () => {
  const component = renderer.create(
    <Link page="http://www.facebook.com">Facebook</Link>,
  );
  let tree = component.toJSON();
  expect(tree).toMatchSnapshot();

  // manually trigger the callback
  renderer.act(() => {
    tree.props.onMouseEnter();
  });
  // re-rendering
  tree = component.toJSON();
  expect(tree).toMatchSnapshot();

  // manually trigger the callback
  renderer.act(() => {
    tree.props.onMouseLeave();
  });
  // re-rendering
  tree = component.toJSON();
  expect(tree).toMatchSnapshot();
});

위와같이 js파일을 추가해준 뒤

yarn test
혹은
yarn jest

명령어를 실행 해 테스트를 진행한다.


참고 글
https://velog.io/@sooyun9600/React-is-not-defined-%EC%97%90%EB%9F%AC-%ED%95%B4%EA%B2%B0

profile
Kotlin, Springboot 2 백엔드 개발자

0개의 댓글