Testing

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.

Isolated Tests

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

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 Test Utilities

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

Those Test Utilities are placed in static Test class (@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<T>(metatype: Metatype<T>), which returns instance of chosen (metatype passed as parameter) controller / component (or null if it is not a part of module).

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.

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

results matching ""

    No results matching ""