具有自定义标头的单元测试拦截器

时间:2018-10-15 18:30:10

标签: javascript angular unit-testing jasmine angular-http-interceptors

我一直在尝试在Angular 6的拦截器中运行测试单元,但是经过反复尝试,我仍然遇到以下错误:

  

错误:预期对标准“按功能匹配:”的一个匹配请求,但没有找到。

我对NG6和它的单元测试有点陌生,在文档中找不到任何内容

这就是我得到的:

令牌服务(由于与后端没有连接而被嘲笑了)

export class TokenService {

token: EventEmitter<any> = new EventEmitter();

findTokenData(): Observable<any> {

    return Observable.create((observer: Observer<object>) => {
        observer.next({ headerName: x-fake, token: fake' });
        observer.complete();
    });
  }
}

其他拦截器

export class RestInterceptor implements HttpInterceptor {

constructor(public tokenService: TokenService) { }

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

    console.log('request intercepted...');

    let authReq: HttpRequest<any>;
    const customHeadersMethods = ['POST', 'PUT', 'DELETE', 'PATCH'];

    // If the requested method is different GET or HEAD request the CSRF token from the service and add it to the headers
    if (customHeadersMethods.indexOf(req.method) !== -1) {
        this.tokenService.findTokenData().subscribe(res => {
            authReq = req.clone({
                headers: req.headers.set(res.headerName, res.token),
            });
        });

    } else {
        authReq = req.clone();
    }

    // send the newly created request
    return next.handle(authReq);
  }
}

其余拦截器规格

describe('RestInterceptor', () => {
const mockTokenService = {
  headerName: 'x-fake',
  token: 'fake'
};

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

  afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
    httpMock.verify();
}));

  it('Should add a custom header', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {

http.post('/data', {}).subscribe(
  response => {
    expect(response).toBeTruthy();
  }
);

const req = httpMock.expectOne(r =>
  r.headers.has(`${mockTokenService.headerName}`) && 
  r.headers.get(`${mockTokenService.headerName}`) === `${mockTokenService.token}`);

expect(req.request.method).toEqual('POST');   

httpMock.verify();
}));
});

有人可以帮助我了解我在想什么吗?

1 个答案:

答案 0 :(得分:1)

我认为您错过了一个事实,TokenService不是简单的值,而是使用findTokenData方法的类,该方法返回Observable。

发生了什么事

您定义了模拟:

const mockTokenService = {
  headerName: 'x-fake',
  token: 'fake'
};

覆盖它:

{
  provide: TokenService,
  useValue: mockTokenService
},

现在Angular将使用此mockTokenService对象作为在RestInterceptor和...中注入的值。

this.tokenService.findTokenData().subscribe(res => {
                      ||
                  undefined  => error

因此,您可以执行以下操作来解决该问题:

import { of } from 'rxjs';
...
const mockToken = {
  headerName: 'x-fake',
  token: 'fake'
};
const mockTokenService = {
  findTokenData: () => {
    return of(mockToken);
  }
};
...
const req = httpMock.expectOne(r =>
  r.headers.has(`${mockToken.headerName}`) &&
  r.headers.get(`${mockToken.headerName}`) === `${mockToken.token}`);