Unit Test Nest JS Filter Catch Method

Viewed 1911

I would like to write unit test for Nest JS Filter that has Catch Method. How do I pass/mock the parameter that is passed when exception happen. How to assert the logger.error is called.

Jest is used for unit test

This is the Nest JS Filter code that capture all exception.


@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.

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%.

1 Answers

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

Related