如何在 NestJs (Jest) 中对模块内的方法进行单元测试

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

我正在为项目添加测试并提高覆盖率。我想知道如何测试 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('*');
  }
}

我想对 AppModule class 中的 configure 方法进行单元测试,但我无法在网上找到有关如何完成的任何文档。任何帮助,将不胜感激。下面是我的基本测试用例,用于查看模块是否编译。

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();
  });
});

如果你想增加覆盖率,你可以忽略 module.ts 文件 在 jest.json 文件中添加以下内容

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

我发现测试方法的最佳方法是创建 AppModule class 的实例调用方法 configure 并模拟消费者。为以后来找这个的人发布答案。

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);
  });
});