Search code examples
angularkarma-jasmineangular-test

Angular unit test HTTP request header


I want to write a unit test to check the headers of a http request. However, the test always ends with an error when I try to access the request header:

it('should have my header', () => {    
  httpClient.get('/someURL').subscribe();
  const req = httpTestingController.match({ method: 'get' });
  console.log(req[0].request.headers);   
  expect(req[0].request.headers.has('Custom-Header')).toEqual(true);
  httpTestingController.verify();
});

The unit test fails with the following error:

TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

I tried out all kinds of ways but I always get this error in the "expect" line where I access the headers. When I log the headers in the console, it looks like this:

LOG: HttpHeaders{normalizedNames: Map{}, lazyUpdate: [Object{name: ..., value: ..., op: ...}], headers: Map{}, lazyInit: HttpHeaders{normalizedNames: Map{}, lazyUpdate: null, headers: Map{}}}

Solution

  • Is there other code in your spec that uses the spread operator?

    See working example below please.

    import { HttpClient, HttpClientModule, HttpHeaders, HttpRequest } from '@angular/common/http';
    import {
      HttpClientTestingModule,
      HttpTestingController,
      TestRequest,
    } from '@angular/common/http/testing';
    import { TestBed, waitForAsync } from '@angular/core/testing';
    
    describe('headers test', () => {
      let httpTestingController: HttpTestingController;
      let httpClient: HttpClient;
    
      beforeEach(
        waitForAsync(() => {
          void TestBed.configureTestingModule({
            imports: [HttpClientTestingModule, HttpClientModule],
          })
            .compileComponents()
            .then(() => {
              httpTestingController = TestBed.inject(HttpTestingController);
              httpClient = TestBed.inject(HttpClient);
            });
        }),
      );
    
      afterEach(() => {
        httpTestingController
          .match((req: HttpRequest<unknown>): boolean => true)
          .forEach((req: TestRequest) => (!req.cancelled ? req.flush({}) : null));
        httpTestingController.verify();
      });
    
      it('should have my header', () => {
        const headers = new HttpHeaders().set('Custom-Header', 'test');
        void httpClient.get('/someURL', { headers }).subscribe();
        const req = httpTestingController.match('/someURL');
        console.warn('req', req);
        console.warn(req[0].request.headers);
        expect(req[0].request.headers.has('Custom-Header')).toEqual(true);
      });
    });