代码之家  ›  专栏  ›  技术社区  ›  Joschi

Jasmine单元测试HttpInterceptor验证方法参数

  •  0
  • Joschi  · 技术社区  · 7 年前

    我有一个角度(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();
    

    但我如何才能验证标题是否已设置?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexander    7 年前

    下面是我用来测试某个拦截器的内容:

    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
    
        }));
      });
    });
    
    推荐文章