spyOn在Angular 6中的Http Interceptor中不起作用 [英] spyOn not working in Http Interceptor in Angular 6

查看:100
本文介绍了spyOn在Angular 6中的Http Interceptor中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试记录http请求响应的HttpInterceptor.我有一个记录请求响应的日志服务.拦截器仅记录GET请求.

I am trying to test HttpInterceptor that logs the response of the http request. I have a log service that logs the response of the request. The interceptor logs only for GET requeststs.

这是我的拦截器:

import { HttpInterceptor, HttpHandler, HttpEvent, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LogService } from './log.service';
import { Injectable } from '@angular/core';

@Injectable({providedIn: 'root'})
export class LoggerInterceptor implements HttpInterceptor {

  constructor(private _log: LogService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(
        tap(event => {
          if (event instanceof HttpResponse) {
            if (req.method === 'GET') {
              this._log.log('I was logged');
            }
          }
        })
      );
  }
}

这是规格文件:

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing';
import { HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
import { HeaderInterceptor } from './add.header.interceptor';
import { LogService } from './log.service';
import { LoggerInterceptor } from './logger.interceptor';

const posts: Array<any> = [
  {
    'userId': 1,
    'id': 1,
    'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et '
  },
  {
    'userId': 1,
    'id': 2,
    'title': 'qui est esse',
    'body': 'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor b'
  }
];

describe('HeaderInterceptor', () => {

  let httpMock: HttpTestingController;
  let logService: LogService;
  let httpClient: HttpClient;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ],
      providers: [
        LogService,
        { provide: HTTP_INTERCEPTORS, useClass: LoggerInterceptor, multi: true }
      ]
    });

    httpMock = TestBed.get(HttpTestingController);
    logService = TestBed.get(LogService);
    httpClient = TestBed.get(HttpClient);
  });

  it('must log the http get request', () => {

    const spy = spyOn(logService, 'log');

    httpClient.get('http://jsonplaceholder.typicode.com/posts')
      .subscribe(
        (data: Array<any>) => {
          expect(data.length).toBe(2);
        }
    );

    const req: TestRequest = httpMock.expectOne('http://jsonplaceholder.typicode.com/posts');
    expect(req.request.headers.has('Content-Type')).toBe(true);
    expect(spy).toHaveBeenCalled();

    req.flush(posts);
  });

  it('must log the http post request', () => {

    const spy = spyOn(logService, 'log');

    httpClient.post('http://jsonplaceholder.typicode.com/posts', posts)
      .subscribe();

    const req: TestRequest = httpMock.expectOne('http://jsonplaceholder.typicode.com/posts');
    expect(req.request.headers.has('Content-Type')).toBe(true);
    expect(spy).not.toHaveBeenCalled();

    req.flush(posts);
  });
});

我有HeaderInterceptor,它向每个http请求添加了Content-Type标头.该拦截器的测试工作正常.

I have HeaderInterceptor that adds Content-Type header to each http request. Testing of that interceptor works fine.

当我尝试测试LoggerInterceptor时,在间谍expect(spy).toHaveBeenCalled();

When I tried to test the LoggerInterceptor, I get error on the spy expect(spy).toHaveBeenCalled();

这是错误:

Error: Expected spy log to have been called.
    at stack (http://localhost:9876/absolute/home/pritambohra/Desktop/testing-in-angular/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:2455:17)
    at buildExpectationResult (http://localhost:9876/absolute/home/pritambohra/Desktop/testing-in-angular/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:2425:14)
    at Spec.expectationResultFactory (http://localhost:9876/absolute/home/pritambohra/Desktop/testing-in-angular/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:901:18)
    at Spec.addExpectationResult (http://localhost:9876/absolute/home/pritambohra/Desktop/testing-in-angular/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:524:34)
    at Expectation.addExpectationResult (http://localhost:9876/absolute/home/pritambohra/Desktop/testing-in-angular/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:845:21)
    at Expectation.toHaveBeenCalled (http://localhost:9876/absolute/home/pritambohra/Desktop/testing-in-angular/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:2369:12)
    at UserContext.<anonymous> (http://localhost:9876/src/app/logger.interceptor.spec.ts?:57:17)
    at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/node_modules/zone.js/dist/zone.js?:388:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/node_modules/zone.js/dist/zone-testing.js?:288:1)
    at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/node_modules/zone.js/dist/zone.js?:387:1)

不太确定我要去哪里错.为了代码覆盖,我正在执行post http调用.我需要解决什么?

Not really sure where I am going wrong. I am executing the post http call for the sake of code-coverage. What do I need to fix?

推荐答案

这可能只是部分答案.

我不是测试专家,所以我不应该尝试解释为什么您的代码失败,但是我相信下面的代码是正确的并且可以进行真实的测试.

I am not expert in testing, so I shouldn't try to explain why your code failing, but I believe the code below is correct and doing true tests.

IMO在GET情况下,您的代码中存在两个问题: -您在期待间谍之后就开始冲洗-应该是相反的方式 -您不是从.subscribe()

IMO there are two problems in your code in the GET case: - you are flushing after expecting the spy - should be the other way around - you are not calling done() from within .subscribe()

尽管您的POST案例代码似乎可以正常工作(除了测试描述似乎不正确,否则不应该是不应该登录"吗?)

Your code for POST case seems to work ok though (except that the test description seems incorrect, shouldn't it be "should NOT log" instead?)

我遗漏了Content-Type标头的检查,因为它由于某种原因而失败(没有时间进一步研究它-好奇地想知道是否能解决它),并且这也不属于您的问题

I have left out the check of Content-Type header as it was failing for some reason (don't have time to investigate it further - will be curious to see if you solve it) and it was not part of your question.

describe('Logger Interceptor', () => {
  let httpMock: HttpTestingController;
  let httpClient: HttpClient;
  let logService: LogService;
  let spy: Function;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: LoggerInterceptor,
          multi: true,
        },
      ],
    });

    httpClient = TestBed.get(HttpClient);
    httpMock = TestBed.get(HttpTestingController);
    logService = TestBed.get(LogService);
    spy = spyOn(logService, 'log');
  });

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

  it('must log the http get request', (done) => {

    httpClient.get('http://jsonplaceholder.typicode.com/posts').subscribe((data: any[]) => {
      expect(data.length).toBe(2);
      done();
    });

    const req: TestRequest = httpMock.expectOne('http://jsonplaceholder.typicode.com/posts');

    req.flush(posts);
    expect(spy).toHaveBeenCalled();
  });

  it('should NOT log the http post request', () => {

    httpClient.post('http://jsonplaceholder.typicode.com/posts', posts)
      .subscribe();

    const req: TestRequest = httpMock.expectOne('http://jsonplaceholder.typicode.com/posts');
    expect(spy).not.toHaveBeenCalled();

    req.flush(posts);
  });
});

如果有人可以解释,我很想知道为什么GET案例要求进行上述更改.

I would be curious to hear why the GET case requires the above changes, should anyone be able to explain.

这篇关于spyOn在Angular 6中的Http Interceptor中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆