我正在尝试测试一个从HTTP请求修改响应的Interceptor。
以下是我的当前代码:
@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' });
});
});
});请注意,我使用的是角10.x.y、Jest26.x.y和Spectator 5.x.y。
发布于 2020-08-31 14:16:32
我能够得到拦截方法来采取以下措施。根据需要修改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‘来满足接口。
https://stackoverflow.com/questions/63653206
复制相似问题