【发布时间】:2020-03-30 23:22:46
【问题描述】:
这是我用 Typescript 为 Nodejs/Nestjs 编写的 BadRequestExceptionFilter
@Catch(BadRequestException)
export class BadRequestExceptionFilter implements ExceptionFilter {
constructor(private logger: AppLoggerService) {}
catch(exception: BadRequestException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const status =
exception instanceof BadRequestException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message = {
Title: exception.message.error,
Type: 'Exception - BadRequestExceptionFilter',
Detail: exception.message,
Status: '',
};
this.logger.error(message, '');
response.code(status).send({
statusCode: status,
...(exception.getResponse() as object),
timestamp: 'Exception - BadRequestException' + new Date().toISOString(),
});
}
}
这是我的单元测试和 2 断言在这里完成。 第一个 assert 是检查是否调用了 mockLogger.error。这是工作。 第二个断言检查是否调用了 response.code(status).send()。 但得到这个错误。 期望(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
const mockLogger = { error: jest.fn() };
const mockContext: any = {
switchToHttp: () => ({
getRequest: () => ({
url: 'mock-url',
}),
getResponse: () => {
const response = {
code: jest.fn().mockReturnThis(),
send: jest.fn().mockReturnThis(),
};
return response;
},
}),
};
describe('BadRequestExceptionFilter', () => {
let filter: BadRequestExceptionFilter;
beforeEach(() => {
filter = new BadRequestExceptionFilter(mockLogger as any);
});
it('should catch and log the error', () => {
const mockException: BadRequestException = new BadRequestException();
mockException.name = 'BadRequestException';
mockException.getResponse = jest.fn().mockReturnValue(of('getResponse'));
mockException.getStatus = () => 404;
jest.fn(mockContext.switchToHttp().getResponse().send);
filter.catch(mockException, mockContext);
expect(mockLogger.error).toBeCalled();
expect(
mockContext
.switchToHttp()
.getResponse()
.code().send,
).toBeCalled();
});
});
【问题讨论】:
-
您找到解决方案了吗?我对此有点卡住了。
-
@tsadkanyitbarek 检查下面我的答案,我已经成功编写测试用例了。
标签: node.js typescript unit-testing jestjs nestjs