我正在尝试测试一个用于修改HTTP请求响应的拦截器。
这是我当前的代码:
@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) }),
),
);
}
}
以及到目前为止我所拥有的相应测试文件:
describe(ResponseCamelCaseInterceptor.name, () => {
const createService = createServiceFactory(ResponseCamelCaseInterceptor);
test('some description', () => {
const { service } = createService();
const fakeHttpRequest = new HttpRequest('POST', 'https://...', { custom_key: '1' });
service.intercept(fakeHttpRequest, 'what should I put here for HttpHandler?').subscribe(() => {
// expect(httpResponse.body).toStrictEqual({ customKey: '1' });
});
});
});
注意,我使用的是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。
这里的关键是,要进行mock,需要使用jest.fn((来模拟函数。为了让TypeScript将mock识别为正确的类,您需要通过实现"handle"来满足接口。