카테고리 없음

TypeScript Jest 테스트 환경 설정 (리트코드 문제 풀이용)

쪽제비 2025. 2. 22. 08:39

리트코드에서 TypeScript 문제를 풀다 보면 로컬에서 테스트가 필요할 때가 많습니다. 이번 글에서는 Jest를 활용하여 TypeScript 테스트 환경을 구성하는 방법을 단계별로 설명합니다.


1️⃣ 프로젝트 폴더 생성 및 초기화

먼저, 프로젝트를 위한 폴더를 만들고 package.json을 초기화합니다.

mkdir leetcode-ts
cd leetcode-ts
yarn init -y

이제 package.json이 생성되었습니다.


2️⃣ Jest 및 TypeScript 설치

테스트 실행을 위해 Jest와 TypeScript 관련 패키지를 설치합니다.

yarn add --dev jest ts-jest @types/jest typescript

설치된 패키지:

  • jest: 테스트 프레임워크
  • ts-jest: Jest에서 TypeScript 실행 가능하게 함
  • @types/jest: TypeScript용 Jest 타입 정의
  • typescript: TypeScript 지원

3️⃣ TypeScript 설정 (tsconfig.json 생성)

TypeScript를 사용하려면 tsconfig.json 파일을 생성하고 아래 설정을 추가해야 합니다.

npx tsc --init

📌 tsconfig.json 수정:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

4️⃣ Jest 설정 (jest.config.js 생성)

Jest를 TypeScript에서 사용할 수 있도록 설정 파일을 생성합니다.

npx ts-jest config:init

📌 jest.config.js 확인:

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

5️⃣ 테스트할 코드 작성 (solution.ts)

테스트할 코드를 작성할 solution.ts 파일을 만듭니다.

mkdir src
touch src/solution.ts

📌 src/solution.ts 내용:

export function add(a: number, b: number): number {
  return a + b;
}

6️⃣ Jest 테스트 파일 작성 (solution.test.ts)

테스트 파일을 작성합니다.

mkdir tests
touch tests/solution.test.ts

📌 tests/solution.test.ts 내용:

import { add } from '../src/solution';

test('add function works correctly', () => {
  expect(add(2, 3)).toBe(5);
  expect(add(-1, 1)).toBe(0);
});

7️⃣ Jest 테스트 실행

테스트를 실행하려면 아래 명령어를 입력합니다.

yarn jest

📌 실행 결과 (성공 시):

PASS  tests/solution.test.ts
✓ add function works correctly (3 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.2 s

🎯 최종 프로젝트 구조

leetcode-ts/
├── node_modules/
├── src/
│   ├── solution.ts
├── tests/
│   ├── solution.test.ts
├── jest.config.js
├── package.json
├── tsconfig.json
├── yarn.lock

이제 TypeScript 환경에서 Jest를 활용하여 리트코드 문제를 로컬에서 테스트할 수 있습니다! 🚀

➡️ 추가 질문이 있다면 댓글로 남겨주세요! 😊