Home > Enterprise >  How to Unit Test a method inside a module in NestJs (Jest)
How to Unit Test a method inside a module in NestJs (Jest)

Time:04-23

I'm adding tests on a project and improving coverage. I would like to know how can I test a method defined inside a module definition in NestJs.

import { MiddlewareConsumer, Module } from '@nestjs/common';
import { AppController } from './controllers/app.controller';
import { LoggerController } from './controllers/logger.controller';
import { LoggingModule } from './logging/logging.module';
import LogsMiddleware from './logging/logging.middleware';

@Module({
  imports: [
    LoggingModule,
  ],
  controllers: [
    LoggerController,
    AppController
  ],
})
export class AppModule {
  // Middleware to log the request and respone for each RestFul/GraphQl routes
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LogsMiddleware).forRoutes('*');
  }
}

I want to unit test the configure method inside the AppModule class but I cannot find any documentation online how it is to be done. Any help would be appreciated. Below is my basic test case to see if the module compiles.

import { Test, TestingModule } from '@nestjs/testing';
import { AppModule } from './app.module';

describe('AppModule', () => {
  let testModule: TestingModule;

  beforeEach(async () => {
    testModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
  });

  it('should validate the app module', () => {
    expect(testModule).toBeDefined();
  });
});

CodePudding user response:

If you want to increase the coverage, you can just ignore the module.ts files by adding following in the jest.json file

"coveragePathIgnorePatterns": [
    ".module.ts",
  ]

CodePudding user response:

I found that the best way to test the method was create a instance of the AppModule class call the method configure and mock the consumer. Posting the answer for anyone who comes looking for this in the future.

app.module.spec.ts

import { createMock } from '@golevelup/ts-jest';
import { MiddlewareConsumer } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { AppModule } from './app.module';
import LogsMiddleware from './logging/logging.middleware';

describe('AppModule', () => {
  let testModule: TestingModule;

  const middlewareConsumer = createMock<MiddlewareConsumer>();
  beforeEach(async () => {
    testModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
  });

  it('should validate the app module', () => {
    expect(testModule).toBeDefined();
  });

  it('should configure the middleware', () => {
    const app = new AppModule();
    app.configure(middlewareConsumer);
    expect(middlewareConsumer.apply).toHaveBeenCalledWith(LogsMiddleware);
  });
});

  • Related