如何解决使用Jest和Spectator测试Angular拦截器的响应
这是我当前的代码:
vars()
到目前为止,我有及其对应的测试文件:
@Injectable()
export class ResponseCamelCaseInterceptor implements HttpInterceptor {
intercept(
httpRequest: HttpRequest<Record<string,unkNown>>,httpHandler: HttpHandler,): Observable<HttpEvent<Record<string,unkNown>>> {
return httpHandler.handle(httpRequest).pipe(
filter(
(value): value is HttpResponse<Record<string,unkNown>> =>
value instanceof HttpResponse,),filter(({ body }) => isPlainObject(body)),map(httpEvent =>
httpEvent.clone({ body: snaketoCamelCase(httpEvent.body) }),);
}
}
请注意,我正在使用Angular 10.x.y,Jest 26.x.y和spectator 5.x.y。
解决方法
我能够获得拦截方法来采取以下措施。根据需要修改mockHandler.handle返回。
const mockHandler = {
handle: jest.fn(() => of(new HttpResponse({status: 200,body: {data: 'thisIsWhatImTesting'}})))
};
spectator.service.intercept(new HttpRequest<any>(HttpMethod.GET,'/api'),mockHandler)
.subscribe((response: HttpResponse<any>) => {
expect(response.body).toStrictEqual({customKey: '1'});
});
在订阅lambda中,您需要指定响应作为输入。这应该是拦截器处理后的HttpResponse。
这里的关键是要开玩笑地模拟您需要使用jest.fn()来模拟该函数。为了使TypeScript能够将模拟物识别为正确的类,您需要通过实现'handle'来满足接口的要求。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。