Files
TK-FB-Project/api.hyungi.net/tests/README.md
Hyungi Ahn b67362a733 feat: Introduce knex for database migrations
- Adds knex.js to manage database schema changes systematically.
- Creates an initial migration file based on `hyungi_schema_v2.sql` to represent the current database state.
- Adds npm scripts (`db:migrate`, `db:rollback`, etc.) for easy execution of migration tasks.
- Archives legacy SQL files and old migration scripts into the `db_archive/` directory to prevent confusion and clean up the project structure.
2025-12-19 09:43:09 +09:00

4.3 KiB

테스트 시작하기

빠른 시작

1단계: 테스트 패키지 설치

cd /Users/hyungiahn/Documents/code/TK-FB-Project/api.hyungi.net
npm install

2단계: 첫 번째 테스트 실행

# 모든 테스트 실행
npm test

# 특정 파일만 테스트
npm test -- tests/unit/services/workReportService.test.js

# Watch 모드 (파일 변경 시 자동 재실행)
npm run test:watch

3단계: 커버리지 확인

# 커버리지와 함께 테스트 실행
npm run test:coverage

# 커버리지 리포트 HTML 보기
open coverage/lcov-report/index.html

디렉토리 구조

tests/
├── README.md                           # 이 파일
├── setup.js                            # Jest 전역 설정
├── helpers/
│   └── mockData.js                     # 테스트용 더미 데이터
├── unit/
│   ├── services/                       # 서비스 레이어 테스트
│   │   └── workReportService.test.js   # ✅ 작성 완료 (예제)
│   ├── controllers/                    # 컨트롤러 테스트 (미작성)
│   └── models/                         # 모델 테스트 (미작성)
└── integration/                        # 통합 테스트 (미작성)

다음 단계: 테스트 파일 작성

우선순위 1: 서비스 레이어 테스트 작성

다음 서비스들에 대한 테스트 파일을 작성하세요:

tests/unit/services/
├── workReportService.test.js          # ✅ 완료
├── attendanceService.test.js          # ⬜ TODO
├── dailyWorkReportService.test.js     # ⬜ TODO
├── workerService.test.js              # ⬜ TODO (간단)
├── projectService.test.js             # ⬜ TODO (간단)
├── issueTypeService.test.js           # ⬜ TODO (간단)
├── toolsService.test.js               # ⬜ TODO
├── dailyIssueReportService.test.js    # ⬜ TODO
├── uploadService.test.js              # ⬜ TODO (간단)
└── analysisService.test.js            # ⬜ TODO

추천 작성 순서:

  1. workReportService.test.js (이미 완료 - 참고용)
  2. workerService.test.js (간단한 CRUD, 시작하기 좋음)
  3. projectService.test.js (간단한 CRUD)
  4. attendanceService.test.js (복잡도 중간)
  5. 나머지 서비스들...

우선순위 2: 컨트롤러 테스트

서비스 레이어 테스트가 어느정도 완료되면 컨트롤러 테스트를 시작하세요.

우선순위 3: 통합 테스트

마지막으로 실제 HTTP 요청을 테스트하는 통합 테스트를 작성하세요.


예제 테스트 작성 방법

서비스 레이어 테스트 템플릿

const serviceName = require('../../../services/serviceName');
const { ValidationError, NotFoundError, DatabaseError } = require('../../../utils/errors');

// 모델 모킹
jest.mock('../../../models/modelName');
const modelName = require('../../../models/modelName');

describe('ServiceName', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('methodName', () => {
    it('should succeed when valid data provided', async () => {
      // Arrange
      const mockData = { /* ... */ };
      modelName.method.mockResolvedValue(mockData);

      // Act
      const result = await serviceName.methodName(params);

      // Assert
      expect(result).toEqual(expectedResult);
      expect(modelName.method).toHaveBeenCalledWith(expectedParams);
    });

    it('should throw ValidationError when invalid data', async () => {
      // Act & Assert
      await expect(serviceName.methodName(invalidParams))
        .rejects.toThrow(ValidationError);
    });
  });
});

유용한 명령어

# 특정 describe 블록만 테스트
npm test -- --testNamePattern="createWorkReportService"

# 실패한 테스트만 재실행
npm test -- --onlyFailures

# 병렬 실행 비활성화 (디버깅 시)
npm test -- --runInBand

# 상세 출력
npm run test:verbose

목표 커버리지

  • 서비스 레이어: 80% 이상
  • 컨트롤러: 70% 이상
  • 전체: 75% 이상

도움말

전체 가이드는 프로젝트 루트의 TESTING_GUIDE.md를 참고하세요:

cat /Users/hyungiahn/Documents/code/TK-FB-Project/TESTING_GUIDE.md

Happy Testing! 🧪