NestJS Enterprise Backend APIs · 강의

단위 및 종단 간 테스트

Jest와 Supertest를 사용하여 개별 구성 요소에 대한 효과적인 단위 테스트와 전체 API 흐름에 대한 종단 간 테스트를 작성합니다.

레슨 1/611개 단계

단위 및 종단 간 테스트은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 6개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 6개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Test Your NestJS App?

Writing tests is crucial for building robust applications. It helps ensure your code works as expected and prevents regressions when you make changes.

  • Reliability: Confirms features work.
  • Refactoring Confidence: Allows changes without fear.
  • Documentation: Tests show how code should be used.

In NestJS, we often focus on two main types: Unit Tests and End-to-End (E2E) Tests.

Unit Testing: Isolated Checks

Unit tests focus on the smallest testable parts of your application, called 'units'. Think of individual functions, methods, or classes (like a NestJS service).

The goal is to test each unit in isolation, meaning without its external dependencies (like databases, external APIs, or other services). This makes them fast and easy to pinpoint issues.

Jest: Your Testing Buddy

NestJS projects come pre-configured with Jest, a popular JavaScript testing framework. Jest makes writing and running tests straightforward.

You can run your tests directly from your terminal. Let's see a simple example of a Jest test file.

// my-first.spec.ts

describe('Basic Jest Test', () => {
  it('should be true', () => {
    // The 'expect' function is how you assert things
    expect(true).toBe(true);
  });

  it('should compare numbers', () => {
    expect(5).toBeGreaterThan(3);
  });
});

Unit Testing a NestJS Service

Let's test a simple NestJS service that handles user data. We'll use @nestjs/testing to create a test module, allowing us to inject our service and its mocked dependencies.

Here, we're testing a UsersService's findAll() method, ensuring it returns users and interacts correctly with its (mocked) repository.

// users.service.spec.ts
import { Test } from '@nestjs/testing';
import { UsersService } from './users.service'; // Assume this file exists

// Mock the repository to isolate the service
const mockUsersRepo = {
  find: jest.fn(() => Promise.resolve([{ id: 1, name: 'Alice' }])),
};

describe('UsersService Unit Test', () => {
  let service: UsersService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [
        UsersService,
        { provide: 'UserRepository', useValue: mockUsersRepo },
      ],
    }).compile();

    service = module.get<UsersService>(UsersService);
  });

  it('should return an array of users', async () => {
    const result = await service.findAll();
    expect(result).toEqual([{ id: 1, name: 'Alice' }]);
    expect(mockUsersRepo.find).toHaveBeenCalledTimes(1);
  });
});

Mocking for Isolation

Mocking is key in unit testing. It means replacing real dependencies (like a database connection or another service) with controlled, fake versions.

This ensures your test only focuses on the unit itself, not on potential issues in its dependencies. In Jest, jest.fn() creates a mock function you can track and control.

// mock-dependency.spec.ts

const mockLogger = {
  log: jest.fn(), // A mock function
};

class MyComponent {
  constructor(private logger: typeof mockLogger) {}

  doSomething(message: string) {
    this.logger.log(`Doing: ${message}`);
    return `Done: ${message}`;
  }
}

describe('Mocking Example', () => {
  it('should call the mock logger', () => {
    const component = new MyComponent(mockLogger);
    const result = component.doSomething('Hello');

    expect(result).toBe('Done: Hello');
    // Verify the mock function was called with specific arguments
    expect(mockLogger.log).toHaveBeenCalledWith('Doing: Hello');
  });
});

End-to-End (E2E) Testing: Full Flow

While unit tests check small parts, End-to-End (E2E) tests verify the entire system, from the user's perspective. For an API, this means making actual HTTP requests to your running NestJS application.

E2E tests ensure that all components (controllers, services, database, authentication, etc.) work together correctly as a complete flow. They are slower but provide high confidence.

Supertest: API Request Helper

For E2E tests, we need a way to make HTTP requests to our NestJS application. Supertest is a popular library that makes this easy, allowing you to simulate requests and assert on responses.

NestJS's testing utilities integrate well with Supertest, enabling you to spin up a test instance of your application.

E2E Testing a NestJS Controller

Let's write an E2E test for a simple AppController that exposes a GET / endpoint. We'll use @nestjs/testing to create an application instance and supertest to send an HTTP request to it.

This test simulates a client hitting your API and checks the HTTP status code and response body.

// app.e2e-spec.ts
import * as request from 'supertest';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { AppModule } from './../src/app.module'; // Your main app module

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init(); // Initialize the NestJS app
  });

  it('/ (GET) should return "Hello World!"', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!');
  });

  afterAll(async () => {
    await app.close(); // Close the app after tests
  });
});

E2E & Database Management

When running E2E tests, especially those involving databases, you need a strategy for managing test data. This often includes:

  • Dedicated Test Database: Use a separate database instance for tests.
  • Seeding Data: Populate the database with known test data before each test or test suite.
  • Cleaning Up: Clear or reset the database after tests to ensure isolation and prevent test pollution.

This ensures tests are consistent and repeatable.

Quick Check: Testing Types

Consider the following statements about Unit and End-to-End (E2E) testing. Which one is TRUE?

Recap: Unit & E2E Testing

Great job! You've explored the foundations of testing in NestJS:

  • Unit Tests: Focus on isolated components (services, functions), using Jest for fast, precise checks. Mocking is key here.
  • E2E Tests: Validate the entire application flow, from request to response, often using Supertest to simulate HTTP calls. They are slower but provide high confidence in the integrated system.

Both testing types are vital for building reliable and maintainable NestJS applications.

무료로 시작

AI 튜터와 함께 TypeScript을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
20
레슨
76

자주 묻는 질문

“단위 및 종단 간 테스트” 강의는 무료인가요?

네 — “단위 및 종단 간 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 6개의 강의가 포함되어 있습니다.

“단위 및 종단 간 테스트”에서 뭘 배우나요?

Jest와 Supertest를 사용하여 개별 구성 요소에 대한 효과적인 단위 테스트와 전체 API 흐름에 대한 종단 간 테스트를 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 1번째 강의입니다.

“단위 및 종단 간 테스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 단위 및 종단 간 테스트
  2. Hardhat 및 Truffle 프레임워크
  3. API 성능 테스트
  4. 스마트 계약 단위 테스트
  5. Docker 컨테이너화와 Kubernetes
  6. 테스트넷 및 메인넷 배포
← NestJS Enterprise Backend APIs(으)로 돌아가기