Vite 프로젝트에 Jest 추가하기

송기영·2023년 5월 15일
6

리액트

목록 보기
4/5

개요

유닛 테스트를 위해서 Vite 프로젝트에 Jest를 추가하는 방법을 이야기하고자 합니다. 프로젝트 생성방법은 포스팅을 참고하시기 바랍니다.

방법

Jest 패키지 설치

Jest 패키지 사용을 위해 패키지를 설치합니다.

yarn add -D jest @types/jest ts-node ts-jest @testing-library/react identity-obj-proxy jest-environment-jsdom @testing-library/jest-dom jest-svg-transformer

package.json 수정

Jest 실행을 위해 package.json에 아래의 명령어를 추가합니다.

"scripts":{
    ...
    "test": "jest"
 }
    

jest 설정파일 추가

루트 폴더에 jest.config.ts 파일을 생성 후 다음과 같이 입력합니다.

export default {
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
  moduleNameMapper: {
    "^.+\\.svg$": "jest-svg-transformer",
    "\\.(css|less|sass|scss)$": "identity-obj-proxy",
  },
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
};

그리고 루트 폴더에 jest.setup.ts 파일을 생성 후 다음과 같이 입력합니다.

import "@testing-library/jest-dom/extend-expect";

이때 module에 lint에러가 나온다면 .eslintrc.cjs 파일에 아래 내용을 추가합니다.

module.exports = {
  env: {
    ...,
  	module: "node",
  }
}

tsconfig.json

tsconfig.json 파일 compilerOptions 내에 다음과 같이 값을 추가합니다.

{
	"compilerOptions":{
      	...,
		"esModuleInterop": true      
    }
}

테스트 코드 추가

src폴더 내에 __tests__ 폴더를 생성 후 App.test.tsx 파일을 생성 후 아래의 내용을 입력합니다.

// Imports
import { render, screen, fireEvent } from "@testing-library/react";

// To Test
import App from "../App";

// Tests
test("Renders main page correctly", async () => {
  // Setup
  render(<App />);
  const buttonCount = await screen.findByRole("button");
  const codeCount = await screen.queryByText(/The count is now:/);

  // Pre Expecations
  expect(buttonCount.innerHTML).toBe("count is 0");
  // Instead of:
  expect(codeCount).toBeNull();
  expect(codeCount).not.toBeInTheDocuement();

  // Init
  fireEvent.click(buttonCount);
  fireEvent.click(buttonCount);

  // Post Expectations
  expect(buttonCount.innerHTML).toBe("count is 2");
  expect(await screen.queryByText(/The count is now:/)).toBeInTheDocument();
});

APP 파일 수정

조건문 테스트를 위해 App.tsx파일을 수정합니다.

import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";

function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React1</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        {count > 0 ? (
          <p>
            <code>The count is now: {count}</code>
          </p>
        ) : null}
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  );
}

export default App;

테스트 실행

다음 명령어를 입력해 테스트를 진행합니다.

yarn test

정상적으로 테스트가 진행됨을 확일할 수 있습니다.

소스코드

https://github.com/kiyoungsong/vite-jest

레퍼런스
https://codingwithmanny.medium.com/quick-jest-setup-with-vitejs-react-typescript-82f325e4323f

profile
업무하면서 쌓인 노하우를 정리하는 블로그🚀 풀스택 개발자를 지향하고 있습니다👻

5개의 댓글

comment-user-thumbnail
2023년 7월 12일

너무 큰 도움이 되었습니다. 좋은 글을 써주셔서 감사합니다.

1개의 답글
comment-user-thumbnail
2023년 11월 28일

작성자님 궁금한 사항이 있습니다. 패키지 설치를 보면 ts-node 를 연달아서 ts-node ts-node 형식으로 작성하였는데, 혹시 추가할 때 의도가 있나요? 따라해보려고 하는데, 궁금해서 질문 남겨봅니다.

1개의 답글
comment-user-thumbnail
2024년 1월 21일

혹시 똑같이 해보려고 시도중인데 require() of ES Module 같은 오류가 나오는데 혹시 어떻게 하셨는지 알 수 있을까요?

답글 달기