In the previous posts, I have write a lot of testing codes to verify if our application is working as expected.

Nestjs provides integration with with Jest and Supertest out-of-the-box, and testing harness for unit testing and end-to-end (e2e) test.


Nestjs test harness

Like the Angular ‘s TestBed, Nestjs provide a similar Test facilities to assemble the Nestjs components for your testing codes.

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ...
      ],
    }).compile();
    service = module.get<UserService>(UserService);
  });

Similar to the attributes in the @Module decorator, creatTestingModule defines the components that will be used in the tests.

We have demonstrated the methods to test a service in Nestjs applications, eg. in the post.service.spec.ts.

To isolate the dependencies in a service, there are several approaches.

  • Create a fake service to replace the real service, assemble it in the providers .
  • providers: [ { provide: UserService, useClass: FakeUserService } ],
  • Use a mock instance instead.
  • providers: [ provide: UserService, useValue: { send: jest.fn() } ],
  • For simple service providers, you can escape from the Nestjs harness, and create a simple fake dependent service, and use new to instantize your service in the setup hooks.

You can also import a module in Test.createTestingModule.

Test.createTestingModule({
        imports: []
       })

To replace some service in the imported modules, you can override it.

Test.createTestingModule({
        imports: []
       })
       .override(...)

#programming #jest #tdd #nestjs #javascript

How to Test Nest.js applications
42.80 GEEK