简体   繁体   English

Angular 单元测试 HTTP 请求标头

[英]Angular unit test HTTP request header

I want to write a unit test to check the headers of a http request.我想编写一个单元测试来检查 http 请求的标头。 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{}}}

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

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

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