gpt4 book ai didi

node.js - 单元测试 Nest JS Filter Catch 方法

转载 作者:行者123 更新时间:2023-12-03 21:00:10 25 4
gpt4 key购买 nike

我想为具有 Catch 方法的 Nest JS 过滤器编写单元测试。
如何传递/模拟发生异常时传递的参数。
如何断言 logger.error 被调用。

Jest 用于单元测试

这是捕获所有异常的 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,
});
}
}

下面给出了我现有的单元测试代码,需要对 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();
});
});


单元测试的测试覆盖率应该是 100%。

最佳答案

您可以在测试所有服务、 Controller 等时测试过滤器的 catch 方法。无需模拟整个捕获流,因为它位于 nest.js 部分。你的测试看起来像这样

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

关于node.js - 单元测试 Nest JS Filter Catch 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com