I have this API call in my service
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
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
QUESTION
how can I check for my unit test if there is an HttpContext set?
CodePudding user response:
Instead of relying on the http mock, you can use spies
const spy = jasmine.createSpy().and.returnValue(of(EMPTY));
service['httpClient'].post = spy;
service.postSomething();
expect(spy.calls.argsFor(1)[1].context instanceof HttpContext).toBeTrue();