【发布时间】:2020-01-03 21:47:00
【问题描述】:
我找不到任何关于如何在 NestJS 中测试拦截器的解释
这个简单的例子截取了一个 POST 查询以向正文中提供的示例模型添加一个属性。
@Injectable()
export class SubscriberInterceptor implements NestInterceptor {
async intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<ExampleModel>> {
let body: ExampleModel = context.switchToHttp().getRequest().body;
body = {
...body,
addedAttribute: 'example',
};
context.switchToHttp().getRequest().body = body;
return next.handle();
}
}
我想测试拦截函数中发生了什么。
到目前为止:
const interceptor = new SubscriberInterceptor();
describe('SubscriberInterceptor', () => {
it('should be defined', () => {
expect(interceptor).toBeDefined();
});
describe('#intercept', () => {
it('should add the addedAttribute to the body', async () => {
expect(await interceptor.intercept(arg1, arg2)).toBe({ ...bodyMock, addedAttribute: 'example' });
});
});
});
我的问题:我应该只模拟 arg1: ExecutionContext 和 arg2: CallHandler 吗?如果是这样,如何模拟arg1 和arg2?否则我应该如何进行?
【问题讨论】:
标签: typescript unit-testing jestjs interceptor nestjs