当前位置: 首页 > 文档资料 > NestJS 中文文档 >

测试

优质
小牛编辑
133浏览
2023-12-01

测试

Nest gives you a set of test utilities, which boost application testing process. There are two different approaches to test your components and controllers - isolated tests or with dedicated Nest test utilities.

Nest为你提供了一些列的测试工具,这些测试工具可以强化应用程序测试过程。有两种测试组件控制器的方式----隔离测试和专用嵌套测试。

分离测试

Both Nest controllers and components are a simple JavaScript classes. It means, that you could easily create them by yourself:

Nest控制器和组件都是JavaScript的简单的类。也就是说,你可以轻松创建组件和控制器:

const component = new SimpleComponent();

If your class has any dependency, you could use test doubles, for example from such libraries as Jasmine or Sinon.

Nest测试工具

The another way to test your applications building block is to use dedicated Nest Test Utilities.

测试应用程序构建模块的另一个方法是使用专有Nest测试工具。

Those Test Utilities are placed in static Test class (@nestjs/testing module).

这些测试工具放置在静态测试类中(@nestjs/testing module

import { Test } from '@nestjs/testing';

This class provide two methods:

  • createTestingModule(metadata: ModuleMetadata), which receives as an parameter simple module metadata (the same as Module() class). This method creates a Test Module (the same as in real Nest Application) and stores it in memory.
  • get(metatype: Metatype), which returns instance of chosen (metatype passed as parameter) controller / component (or null if it is not a part of module).

该测试类提供两种方法:

  • createTestingModule(metadata:ModuleMetadata),该方法接收简单模块元数据作为一个参数(与Module()类相同)该方法创建一个测试模块(与实际嵌套Nest应用程序相同),并将该模块存储在内存中。
  • get<T>(metatype: Metatype<T>),该方法返回选定的控制器(传递metatype作为参数)/组件的实例(如果该实例不是模块的一部分,则返回null

Example:

示例

Test.createTestingModule({
    controllers: [ UsersController ],
    components: [ UsersService ]
});
const usersService = Test.get<UsersService>(UsersService);

Mocks, spies, stubs

Sometimes you might not want to use a real instance of component / controller. Instead of this - you can use test doubles or custom values / objects.

有时候你可能不行使用实际组件/控制机实例,你可以使用测试替身或者(test doubles)自定义值/对象

const fakeService = {};
Test.createTestingModule({
    controllers: [ UsersController ],
    components: [
        { provide: UsersService, useValue: fakeService }
    ]
});
const usersService = Test.get<UsersService>(UsersService); // mockService