【问题标题】:Jasmine Unit testing HttpInterceptor validating method argumentJasmine 单元测试 Http Interceptor 验证方法参数
【发布时间】:2018-10-05 10:33:15
【问题描述】:

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

但是如何验证标头是否已设置?

【问题讨论】:

    标签: angular typescript unit-testing jasmine


    【解决方案1】:

    这是我用来测试一些拦截器的:

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

    【讨论】:

    • 这对我有帮助。谢谢!
    猜你喜欢
    • 2015-05-31
    • 2016-12-04
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多