簡體   English   中英

茉莉花單元測試HttpInterceptor驗證方法參數

[英]Jasmine Unit testing HttpInterceptor validating method argument

我有一個像這樣的攔截方法的Angular(6)HttpInterceptor:

intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {

    if (this.translationService.currentLang) {
      req = req.clone({
        setHeaders: {
          'Accept-Language': this.translationService.currentLang
        }
      });
    }

    return next.handle(req);
  }

如何使用Jasmine對它進行單元測試,並檢查返回的請求是否包含新的標頭? 我知道我可以用

let next = jasmine.createSpyObj('httpHandler', ['handle']);
next.handle.calls.mostRecent();

但是,如何驗證標頭已設置?

這是我用來測試一些攔截器的內容:

describe(`interceptor: yourinterceptor`, () => { // CHANGE HERE
  let httpMock: HttpTestingController;
  let injector: TestBed;

  function createTestModule(providers: Provider[] = []) {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: YOUR_INTERCEPTOR, // CHANGE HERE
          multi: true
        },
        ...providers
      ]
    });
    injector = getTestBed();
    httpMock = injector.get(HttpTestingController);
  }

  beforeEach(() => {
    // empty
  });

  afterEach(() => {
    httpMock.verify();
  });

  describe('request with headers', () => {
    beforeEach(() => {
      createTestModule();
    });
    it('should make the request with headers', inject([HttpClient], (http: HttpClient) => {
      http.get('/dummy').subscribe();
      const httpRequest: TestRequest = httpMock.expectOne('/dummy');
      expect(httpRequest.request.headers.has("YOUR_HEADER")).toBeTruthy(); // CHANGE HERE

    }));
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM