简体   繁体   English

Angular 中的单元测试 http 上下文

[英]Unit test http context in Angular

I have this API call in my service我的服务中有这个 API 电话

import { HttpContext } from '@angular/common/http';
export const SET_INVALID_TOKEN = new HttpContextToken(() => false);
...
    postSomething() {
        this.httpClient.post<MyModel>(`${this.API_SERVER_ADDRESS}/...`, {...}, { context: new HttpContext().set(SET_INVALID_TOKEN, true) })
    }

The reason I am using this context is to debug invalid token cases to my interceptors.我使用此上下文的原因是为我的拦截器调试无效令牌案例。 You can find more information about this on this article .您可以在这篇文章中找到更多相关信息。 I should mention here that this context is used ONLY for debugging purposes.我应该在这里提到这个上下文仅用于调试目的。 The point is that it should never be forgotten at a production stage.关键是在生产阶段永远不要忘记它。

Here is my unit test for the api call这是我对 api 电话的单元测试

fit('should ...', (done: DoneFn) => {
    let httpTestingController = TestBed.get(HttpTestingController);
    let service = TestBed.get(AnalysisAPIService);
    service.postSomething().subscribe(
        analyses => {
            ...
            done()
        },
        done.fail
    )
    const req = httpTestingController.expectOne(service["API_SERVER_ADDRESS"] + "/...");
    console.log(req.request.context.keys())
    req.flush(AnalysisMock.mockAnalysesResponse)// allows to use the dummy data
    
});

PROBLEM问题

The req.request.context.keys() is an empty object req.request.context.keys()是一个空的 object

QUESTION

how can I check for my unit test if there is an HttpContext set?如果设置了 HttpContext,如何检查我的单元测试?

Instead of relying on the http mock, you can use spies您可以使用间谍而不是依赖 http 模拟


const spy = jasmine.createSpy().and.returnValue(of(EMPTY));

service['httpClient'].post = spy;

service.postSomething();

expect(spy.calls.argsFor(1)[1].context instanceof HttpContext).toBeTrue();

You can provide a callback to HttpTestingController.expectOne and make assertions on the request in the callback function.您可以向HttpTestingController.expectOne提供回调,并在回调 function 中对请求进行断言。

Either by returning true/false for if the request meets your conditions:如果请求满足您的条件,则返回 true/false:

const req = httpController.expectOne((r) => {
  return r.context.get(SET_INVALID_TOKEN);
});
req.flush(mockResponse);

or using explicit expectations (not sure if this is recommended but I like this more):或使用明确的期望(不确定是否推荐这样做,但我更喜欢这样做):

const req = httpController.expectOne((r) => {
  expect(r.context.url).toEqual("https://localhost:3000/blah");
  expect(r.context.get(SET_INVALID_TOKEN).toBeFalse();
  expect(r.headers.get("my-header").toEqual("my-header-value");
  return true;
});
req.flush(mockResponse);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM