Jest를 사용해보자! - 1편

2023. 10. 26. 12:49React

1. Jest를 사용하기 전에

  • Yarn + Typescript + Jest + react-testing-library
  • 프로젝트 생성은
yarn create vite my-react-app --template react-ts
  • 추가로 의존성 설치는
1) yarn add -D typescript
2) yarn add -D jest jest-environment-jsdom
3) yarn add -D @testing-library/jest-dom @testing-library/react @testing-library/user-event
4) yarn add -D @types/jest 
5) yarn add -D babel-jest ts-jest ts-node
  • package.json 에서 scripts 부분 수정.
    "scripts": {
        ...
        "test": "jest"
      },​

2. 제대로 설치되었는지 확인해보자.

  1. 일단 최상단에 __test__ 라는 폴더를 만들고 안에 App.test.tsx 라는 파일을 만들어주었다. test.ts는 무시해도 된다. 
    __test__ 폴더와 App.test.tsx 파일
  2. App.test.tsx 파일에 테스트 코드를 작성한다.
    test("1 + 1 = ", () => {
      expect(1+1).toBe(2);
    })​
    - test(test 진행 시에 보일 문구, function(){} ) 으로 구성되어있다. expect는 어떤 코드 또는 값이 특정 조건을 만족하는지 테스트할 때 사용된다. toBe(value), toEqual(value) 등과 같이 쓰이게 된다.
    위의 코드는 1+1이 2와 일치하는지 확인하는 코드이다. 
  3. 난 yarn을 쓰고 있으니 yarn test 입력.
    yarn test 를 입력했을 때, 나오는 결과 창. PASS 란다.
  4. 위의 화면과 동일하다면 성공이다.

3. 참고자료.

 

4. 다음은?

  • 다음은 버튼 클릭 시, 숫자가 증가한다는 등의 이벤트와 관련된 내용을 해보려고 한다.