简体   繁体   English

单元测试 Nest JS 过滤器捕获方法

[英]Unit Test Nest JS Filter Catch Method

I would like to write unit test for Nest JS Filter that has Catch Method.我想为具有 Catch 方法的 Nest JS 过滤器编写单元测试。 How do I pass/mock the parameter that is passed when exception happen.发生异常时如何传递/模拟传递的参数。 How to assert the logger.error is called.如何断言 logger.error 被调用。

Jest is used for unit test Jest 用于单元测试

This is the Nest JS Filter code that capture all exception.这是捕获所有异常的 Nest JS 过滤器代码。


@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private logger: AppLoggerService) {}

  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const message = {
      Title: exception.name,
      Type: 'Error',
      Detail: exception.message,
      Status: 'Status',
      Extension: '',
    };
    this.logger.error(message, '');

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    response.status(status).send({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}

My existing Unit test code is given below and need to write test on catch method.下面给出了我现有的单元测试代码,需要在 catch 方法上编写测试。

describe('AllExceptionsFilter', () => {
    let allExceptionsFilter: AllExceptionsFilter;
    let appLoggerService: AppLoggerService;

    beforeEach(async () => {
        const loggerOptions = { appPath: process.cwd() }
        const module: TestingModule = await Test.createTestingModule({
            providers: [AllExceptionsFilter,
                {
                    provide: AppLoggerService,
                    useValue: new AppLoggerService(loggerOptions, 'AllExceptionsFilter'),
                },
            ],
        }).compile();
        allExceptionsFilter = module.get<AllExceptionsFilter>(AllExceptionsFilter);
    });

    it('should be defined', () => {
        expect(allExceptionsFilter).toBeDefined();
    });
});

Test coverage of unit test should be 100%.单元测试的测试覆盖率应该是 100%。

You can test the catch method of your filter as you test all your services, controllers etc. There is no need to simulate the whole catch flow as it's on nest.js part.您可以在测试所有服务、控制器等时测试过滤器的 catch 方法。无需模拟整个 catch 流程,因为它位于 nest.js 部分。 Your test is going to look like this您的测试将如下所示

import { ConfigModule } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import configuration from '../config';
import { IneligibleExceptionFilter } from './ineligible.filter';

describe('IneligibleExceptionFilter', () => {
  let service: IneligibleExceptionFilter;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [ConfigModule.forRoot({ isGlobal: true, load: [configuration] })],
      providers: [IneligibleExceptionFilter],
    }).compile();

    service = module.get<IneligibleExceptionFilter>(IneligibleExceptionFilter);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('catch', () => {
    it('my test1', () => {
      // some logic here
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM