0Pricing
NestJS Enterprise Backend APIs · 课时

单元测试与端到端测试

使用 Jest 和 Supertest 为独立组件编写有效的单元测试,并为完整的 API 流程编写端到端测试。

单元测试与端到端测试 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 1 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 6 节课。

「单元测试与端到端测试」这节课中我会学到什么?

使用 Jest 和 Supertest 为独立组件编写有效的单元测试,并为完整的 API 流程编写端到端测试。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 NestJS Enterprise Backend APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 6 节。

「单元测试与端到端测试」课时需要多长时间?

大多数 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