1

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{}}}

1 Answer 1

2

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);
  });
});

Sign up to request clarification or add additional context in comments.

1 Comment

Your code works as well. But mine did, too. The problem was a mocked class, that I was using in my test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.