SHIN STORYSHIN STORY
홈포스트C#TypeScriptNext.jsNode.js시리즈
</>SHIN STORY

sdf

탐색

  • 홈
  • 모든 포스트
  • 시리즈
  • 검색

카테고리

  • C#
  • TypeScript
  • Next.js
  • Node.js
  • 알고리즘
  • 개발 도구

© 2025 Shin Blog. All rights reserved.

GitHubRSS
목록으로
Node.js#JavaScript#Node.js#Backend

Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

SHIN

2026년 5월 6일2분 읽기1
📚

Node.js 실전 팁 20선

20편
  1. 3Node.js Stream으로 대용량 파일 처리하기
  2. 4Worker Threads로 CPU 집약 작업 처리하기
  3. 5cluster 모듈로 멀티코어 CPU 100% 활용하기
  4. 6child_process로 외부 명령 실행하기
  5. 7fs/promises로 파일 시스템 다루기
  6. 20Node.js Event Loop 완전 정복
  7. 20Node.js path 모듈 완전 정복
  8. 20환경 변수 관리 — .env, dotenv, 그리고 검증
  9. 20EventEmitter 패턴으로 느슨한 결합 구현하기
  10. 20Node.js crypto 모듈로 해싱과 암호화 구현하기
  11. 20Node.js 메모리 누수 찾고 수정하기
  12. 20Express 미들웨어 패턴과 에러 처리
  13. 20Node.js CJS vs ESM 모듈 시스템 완전 정리
  14. 20Node.js Buffer와 인코딩 완전 가이드
  15. 20PM2로 Node.js 프로세스 관리하기
  16. 20Node.js HTTP 서버 직접 구현하기
  17. 20Node.js 성능 프로파일링 실전 가이드
  18. 20Node.js npm 스크립트 완전 활용하기
  19. 20Node.js 보안 체크리스트 10가지
  20. Node.js 테스팅 전략 — 단위, 통합, E2E 테스트현재

Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

좋은 테스트는 "코드가 무엇을 해야 하는가"를 문서화하고, 리팩토링 시 안전망이 됩니다.

Vitest 설정

CODE
npm install -D vitest @vitest/coverage-v8 supertest
CODE
// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    environment: 'node',
    globals: true,
    coverage: {
      provider: 'v8',
      reporter: ['text', 'lcov'],
      exclude: ['node_modules', 'dist', '**/*.d.ts'],
    },
  },
});

단위 테스트

CODE
// src/utils/formatDate.ts
export function formatDate(date: Date, locale = 'ko-KR'): string {
  return new Intl.DateTimeFormat(locale, {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  }).format(date);
}
CODE
// src/utils/formatDate.test.ts
import { describe, it, expect } from 'vitest';
import { formatDate } from './formatDate';

describe('formatDate', () => {
  it('한국어 날짜 형식으로 변환한다', () => {
    const date = new Date('2024-01-15');
    expect(formatDate(date)).toBe('2024년 1월 15일');
  });

  it('영어 형식도 지원한다', () => {
    const date = new Date('2024-01-15');
    expect(formatDate(date, 'en-US')).toMatch(/January 15, 2024/);
  });
});

통합 테스트 (Supertest)

CODE
// tests/users.test.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import request from 'supertest';
import { app } from '../src/app';
import { prisma } from '../src/lib/prisma';

beforeAll(async () => {
  await prisma.$executeRaw`DELETE FROM users WHERE email LIKE '%@test.com'`;
});

afterAll(async () => {
  await prisma.$disconnect();
});

describe('POST /api/users', () => {
  it('유효한 데이터로 유저를 생성한다', async () => {
    const res = await request(app)
      .post('/api/users')
      .send({ email: 'test@test.com', name: '테스트' })
      .expect(201);

    expect(res.body).toMatchObject({ email: 'test@test.com' });
    expect(res.body.id).toBeDefined();
  });

  it('이메일 없으면 400을 반환한다', async () => {
    await request(app)
      .post('/api/users')
      .send({ name: '테스트' })
      .expect(400);
  });
});

vi.mock으로 모킹

CODE
import { vi, describe, it, expect } from 'vitest';
import { sendEmail } from '../src/services/email';

vi.mock('../src/services/email', () => ({
  sendEmail: vi.fn().mockResolvedValue({ id: 'mock-123' }),
}));

it('주문 생성 시 이메일을 발송한다', async () => {
  await orderService.createOrder({ userId: 1, items: [] });
  expect(sendEmail).toHaveBeenCalledWith(
    expect.objectContaining({ subject: '주문 확인' })
  );
});

스냅샷 테스트

CODE
it('API 응답 구조가 변경되지 않는다', async () => {
  const res = await request(app).get('/api/config').expect(200);
  expect(res.body).toMatchSnapshot();
});

테스트 커버리지 & CI

CODE
{
  "scripts": {
    "test": "vitest run",
    "test:coverage": "vitest run --coverage --coverage.thresholds.statements=80"
  }
}

테스트 피라미드: 단위 테스트(많음, 빠름) → 통합 테스트(중간) → E2E 테스트(적음, 느림). 각 레이어가 서로 다른 종류의 버그를 잡습니다.

공유
S

SHIN

.NET 개발자입니다

GitHub
Docker로 개발 환경 구축하기

이전 포스트

Docker로 개발 환경 구축하기

다음 포스트

Devexpress Winform Tip

Devexpress Winform Tip

같은 카테고리 포스트

Node.js 보안 체크리스트 10가지

Node.js 보안 체크리스트 10가지

2026년 5월 5일· 2분
Node.js npm 스크립트 완전 활용하기

Node.js npm 스크립트 완전 활용하기

2026년 5월 4일· 1분
Node.js 성능 프로파일링 실전 가이드

Node.js 성능 프로파일링 실전 가이드

2026년 5월 3일· 2분

댓글