Typescript 如何对嵌套拦截器进行单元测试
我正在寻找一些关于在Typescript 如何对嵌套拦截器进行单元测试,typescript,nestjs,Typescript,Nestjs,我正在寻找一些关于在Nestjs中对拦截器进行单元测试的见解,请说明我对单元测试的有限理解,因为我对它们还是相当陌生的,所以尽管如此,请随意解释那些看起来很琐碎的概念,我还是会很感激的 为了回答这个问题,我将借用Nestjs文档中的代码,特别是LoggingInterceptor,因为这是我在项目中实现的代码 这是官方文档中的日志拦截器。 从'rxjs'导入{Observable}; 从“rxjs/operators”导入{tap}; @可注射() 导出类LoggingInterceptor实现
Nestjs
中对拦截器进行单元测试的见解,请说明我对单元测试的有限理解,因为我对它们还是相当陌生的,所以尽管如此,请随意解释那些看起来很琐碎的概念,我还是会很感激的
为了回答这个问题,我将借用Nestjs
文档中的代码,特别是LoggingInterceptor
,因为这是我在项目中实现的代码
这是官方文档中的日志拦截器。
从'rxjs'导入{Observable};
从“rxjs/operators”导入{tap};
@可注射()
导出类LoggingInterceptor实现NestInterceptor{
拦截(上下文:ExecutionContext,下一步:CallHandler):可观察{
log('Before…');
const now=Date.now();
下一个返回
.handle()
.烟斗(
轻触(()=>console.log(`After…${Date.now()-now}ms`),
);
}
}
我曾经尝试过几次,但都失败了,设置了一个简单的单元测试,只显示了
控制台。log
被调用了两次,一次在下一次调用之前,一次在之后。您可以通过以下方式轻松创建记录器拦截器的单元测试:
it('should log to console', async done => {
const mockHandler: CallHandler = {
handle: () => throwError(new Error('try and retry')),
};
const mockExecutionContext = ({} as unknown) as ExecutionContext;
const spy = jest.spyOn(console, 'log');
loggerInterceptor
.intercept(mockExecutionContext, mockHandler)
.subscribe(
_ => _,
() => {
expect(spy).toBeCalled();
done();
},
)
.unsubscribe();
});
it('should log to console', async done => {
const mockHandler: CallHandler = {
handle: () => throwError(new Error('try and retry')),
};
const mockExecutionContext = ({} as unknown) as ExecutionContext;
const spy = jest.spyOn(console, 'log');
loggerInterceptor
.intercept(mockExecutionContext, mockHandler)
.subscribe(
_ => _,
() => {
expect(spy).toBeCalled();
done();
},
)
.unsubscribe();
});