Testing

Automated testing is considered an essential part of any serious software development effort. Automation makes it easy to repeat individual tests or test suites quickly and easily during development. This helps ensure that releases meet quality and performance goals. Automation helps increase coverage and provides a faster feedback loop to developers. Automation both increases the productivity of individual developers and ensures that tests are run at critical development lifecycle junctures, such as source code control check-in, feature integration, and version release.

Such tests often span a variety of types, including unit tests, end-to-end (e2e) tests, integration tests, and so on. While the benefits are unquestionable, it can be tedious to set them up. Nest strives to promote development best practices, including effective testing, so it includes features such as the following to help developers and teams build and automate tests. Nest:

  • automatically scaffolds default unit tests for components and e2e tests for applications
  • provides default tooling (such as a test runner that builds an isolated module/application loader)
  • provides integration with Jest and Supertest out-of-the-box, while remaining agnostic to testing tools
  • makes the Nest dependency injection system available in the testing environment for easily mocking components

As mentioned, you can use any testing framework that you like, as Nest doesn’t force any specific tooling. Simply replace the elements needed (such as the test runner), and you will still enjoy the benefits of Nest’s ready-made testing facilities.

Installation

To get started, first install the required package:

  1. $ npm i --save-dev @nestjs/testing

Unit testing

In the following example, we test two classes: CatsController and CatsService. As mentioned, Jest is provided as the default testing framework. It serves as a test-runner and also provides assert functions and test-double utilities that help with mocking, spying, etc. In the following basic test, we manually instantiate these classes, and ensure that the controller and service fulfill their API contract.

  1. @@filename(cats.controller.spec)
  2. import { CatsController } from './cats.controller';
  3. import { CatsService } from './cats.service';
  4. describe('CatsController', () => {
  5. let catsController: CatsController;
  6. let catsService: CatsService;
  7. beforeEach(() => {
  8. catsService = new CatsService();
  9. catsController = new CatsController(catsService);
  10. });
  11. describe('findAll', () => {
  12. it('should return an array of cats', async () => {
  13. const result = ['test'];
  14. jest.spyOn(catsService, 'findAll').mockImplementation(() => result);
  15. expect(await catsController.findAll()).toBe(result);
  16. });
  17. });
  18. });
  19. @@switch
  20. import { CatsController } from './cats.controller';
  21. import { CatsService } from './cats.service';
  22. describe('CatsController', () => {
  23. let catsController;
  24. let catsService;
  25. beforeEach(() => {
  26. catsService = new CatsService();
  27. catsController = new CatsController(catsService);
  28. });
  29. describe('findAll', () => {
  30. it('should return an array of cats', async () => {
  31. const result = ['test'];
  32. jest.spyOn(catsService, 'findAll').mockImplementation(() => result);
  33. expect(await catsController.findAll()).toBe(result);
  34. });
  35. });
  36. });

info Hint Keep your test files located near the classes they test. Testing files should have a .spec or .test suffix.

Because the above sample is trivial, we aren’t really testing anything Nest-specific. Indeed, we aren’t even using dependency injection (notice that we pass an instance of CatsService to our catsController). This form of testing - where we manually instantiate the classes being tested - is often called isolated testing as it is independent from the framework. Let’s introduce some more advanced capabilities that help you test applications that make more extensive use of Nest features.

Testing utilities

The @nestjs/testing package provides a set of utilities that enable a more robust testing process. Let’s rewrite the previous example using the built-in Test class:

  1. @@filename(cats.controller.spec)
  2. import { Test } from '@nestjs/testing';
  3. import { CatsController } from './cats.controller';
  4. import { CatsService } from './cats.service';
  5. describe('CatsController', () => {
  6. let catsController: CatsController;
  7. let catsService: CatsService;
  8. beforeEach(async () => {
  9. const module = await Test.createTestingModule({
  10. controllers: [CatsController],
  11. providers: [CatsService],
  12. }).compile();
  13. catsService = module.get<CatsService>(CatsService);
  14. catsController = module.get<CatsController>(CatsController);
  15. });
  16. describe('findAll', () => {
  17. it('should return an array of cats', async () => {
  18. const result = ['test'];
  19. jest.spyOn(catsService, 'findAll').mockImplementation(() => result);
  20. expect(await catsController.findAll()).toBe(result);
  21. });
  22. });
  23. });
  24. @@switch
  25. import { Test } from '@nestjs/testing';
  26. import { CatsController } from './cats.controller';
  27. import { CatsService } from './cats.service';
  28. describe('CatsController', () => {
  29. let catsController;
  30. let catsService;
  31. beforeEach(async () => {
  32. const module = await Test.createTestingModule({
  33. controllers: [CatsController],
  34. providers: [CatsService],
  35. }).compile();
  36. catsService = module.get(CatsService);
  37. catsController = module.get(CatsController);
  38. });
  39. describe('findAll', () => {
  40. it('should return an array of cats', async () => {
  41. const result = ['test'];
  42. jest.spyOn(catsService, 'findAll').mockImplementation(() => result);
  43. expect(await catsController.findAll()).toBe(result);
  44. });
  45. });
  46. });

The Test class is useful for providing an application execution context that essentially mocks the full Nest runtime, but gives you hooks that make it easy to manage class instances, including mocking and overriding. The Test class has a createTestingModule() method that takes a module metadata object as its argument (the same object you pass to the @Module() decorator). This method returns a TestingModule instance which in turn provides a few methods. For unit tests, the important one is the compile() method. This method bootstraps a module with its dependencies (similar to the way an application is bootstrapped in the conventional main.ts file using NestFactory.create()), and returns a module that is ready for testing.

info Hint The compile() method is asynchronous and therefore has to be awaited. Once the module is compiled you can retrieve any instance it declares (controllers and providers) using the get() method.

Instead of using the production version of any provider, you can override it with a custom provider for testing purposes. For example, you can mock a database service instead of connecting to a live database. We’ll cover overrides in the next section, but they’re available for unit tests as well.

End-to-end testing

Unlike unit testing, which focuses on individual modules and classes, end-to-end (e2e) testing covers the interaction of classes and modules at a more aggregate level — closer to the kind of interaction that end-users will have with the production system. As an application grows, it becomes hard to manually test the end-to-end behavior of each API endpoint. Automated end-to-end tests help us ensure that the overall behavior of the system is correct and meets project requirements. To perform e2e tests we use a similar configuration to the one we just covered in unit testing. In addition, Nest makes it easy to use the Supertest library to simulate HTTP requests.

  1. @@filename(cats.e2e-spec)
  2. import * as request from 'supertest';
  3. import { Test } from '@nestjs/testing';
  4. import { CatsModule } from '../../src/cats/cats.module';
  5. import { CatsService } from '../../src/cats/cats.service';
  6. import { INestApplication } from '@nestjs/common';
  7. describe('Cats', () => {
  8. let app: INestApplication;
  9. let catsService = { findAll: () => ['test'] };
  10. beforeAll(async () => {
  11. const module = await Test.createTestingModule({
  12. imports: [CatsModule],
  13. })
  14. .overrideProvider(CatsService)
  15. .useValue(catsService)
  16. .compile();
  17. app = module.createNestApplication();
  18. await app.init();
  19. });
  20. it(`/GET cats`, () => {
  21. return request(app.getHttpServer())
  22. .get('/cats')
  23. .expect(200)
  24. .expect({
  25. data: catsService.findAll(),
  26. });
  27. });
  28. afterAll(async () => {
  29. await app.close();
  30. });
  31. });
  32. @@switch
  33. import * as request from 'supertest';
  34. import { Test } from '@nestjs/testing';
  35. import { CatsModule } from '../../src/cats/cats.module';
  36. import { CatsService } from '../../src/cats/cats.service';
  37. import { INestApplication } from '@nestjs/common';
  38. describe('Cats', () => {
  39. let app: INestApplication;
  40. let catsService = { findAll: () => ['test'] };
  41. beforeAll(async () => {
  42. const module = await Test.createTestingModule({
  43. imports: [CatsModule],
  44. })
  45. .overrideProvider(CatsService)
  46. .useValue(catsService)
  47. .compile();
  48. app = module.createNestApplication();
  49. await app.init();
  50. });
  51. it(`/GET cats`, () => {
  52. return request(app.getHttpServer())
  53. .get('/cats')
  54. .expect(200)
  55. .expect({
  56. data: catsService.findAll(),
  57. });
  58. });
  59. afterAll(async () => {
  60. await app.close();
  61. });
  62. });

In this example, we build on some of the concepts described earlier. In addition to the compile() method we used earlier, we now use the createNestApplication() method to instantiate a full Nest runtime environment. We save a reference to the running app in our app variable so we can use it to simulate HTTP requests.

We simulate HTTP tests using the request() function from Supertest. We want these HTTP requests to route to our running Nest app, so we pass the request() function a reference to the HTTP listener that underlies Nest (which, in turn, may be provided by the Express platform). Hence the construction request(app.getHttpServer()). The call to request() hands us a wrapped HTTP Server, now connected to the Nest app, which exposes methods to simulate an actual HTTP request. For example, using request(...).get('/cats') will initiate a request to the Nest app that is identical to an actual HTTP request like get '/cats‘ coming in over the network.

In this example, we also provide an alternate (test-double) implementation of the CatsService which simply returns a hard-coded value that we can test for. Use overrideProvider() to provide such an alternate implementation. Similarly, Nest provides methods to override guards, interceptors, filters and pipes with theoverrideGuard(), overrideInterceptor(), overrideFilter(), and overridePipe() methods respectively.

Each of the override methods returns an object with 3 different methods that mirror those described for custom providers:

  • useClass: you supply a class that will be instantiated to provide the instance to override the object (provider, guard, etc.).
  • useValue: you supply an instance that will override the object.
  • useFactory: you supply a function that returns an instance that will override the object.

Each of the override method types, in turn, returns the TestingModule instance, and can thus be chained with other methods in the fluent style. You should use compile() at the end of such a chain to cause Nest to instantiate and initialize the module.

The compiled module has several useful methods, as described in the following table:

createNestApplication() Creates and returns a Nest application (INestApplication instance) based on the given module. Note that you must manually initialize the application using the init() method.
createNestMicroservice() Creates and returns a Nest microservice (INestMicroservice instance) based on the given module.
get() Retrieves an instance of a controller or provider (including guards, filters, etc.) available in the application context.
select() Navigates through the module’s dependency graph; can be used to retrieve a specific instance from the selected module (used along with strict mode (strict: true) in get() method).

info Hint Keep your e2e test files inside the e2e directory. The testing files should have a .e2e-spec or .e2e-test suffix.