In a few other posts I wrote about how to access custom headers in an Angular GET HTTP call and how to set custom headers in an Angular PUT or POST call.

But, how do I test those methods creating a custom header? It isn't hard.

Let's assume I'm trying to test code like this:

view plain print about
1let mySavedCustomHeader;
2makeServiceCall(): Observable<object | MyCustomClass> {
3 return this.http.get(`url`, { observe: 'response' })
4 map((response: HttpResponse<object>) =>
{
5 // save header
6 mySavedCustomHeader = response.headers.get('my-custom-header-name');
7
8 // other processing as needed
9 Object.assign(new MyCustomClass(), response.body)
10 return myCustomResponse;
11 })
12}

There is a method, presumably on a service. It makes a service call to some service and passes in a configuration object that says "return the response. The result handler accesses the header object in order to get our custom header returned from the service. Then it does other processing. this should be relatively straight forward.

So, how do we test this?

First, set up your TestBed, be sure to load the HttpClientTestingModule:

view plain print about
1let service, httpMock;
2
3beforeEach(async(() =>
{
4 TestBed.configureTestingModule({
5 imports: [
6 HttpClientTestingModule
7 ],
8 providers: [
9 MyCustomService,
10 ]
11 }).compileComponents()
12 .then (() => {
13 service = TestBed.get(MyCustomService
14 httpMock = TestBed.get(HttpTestingController);
15 });
16}));

This code saves the service and httpMock values for later use in our test.

Start the test:

view plain print about
1it('should call REST Endpoint with custom header', () => {
2 // all our other code will go here
3});

First thing we want to do is make the service method. It returns an Observable so we'll subscribe to it and add some tests.

view plain print about
1service.makeServiceCall().subscribe((value) => {
2 expect(service.mySavedCustomHeader).toBe('something');
3});

Inside the service result handle we check for the custom header value on the service and make sure it was set. The assertions inside the result handler will run as the last piece of this method, even though the come first. Nothing has triggered the result handler yet.

How look for the mock HTTP call

view plain print about
1const request = httpMock.expectOne('url');

I'll often run some assertions on the requestt

view plain print about
1expect(request.method).toEqual('get');

Now create an HTTPHeader object:

view plain print about
1const HttpHeader = {}
2HttpHeader['my-custom-header-name'] = 'something';

And finally, flush the HTTP call:

view plain print about
1req.flush(SomeCustomObjectWeDidNotCreateHere, {
2 headers: new HttpHraders(HttpHeader)
3});

And that should be all you need to pass your custom header to the from your test into your service code.