简体   繁体   English

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

[英]Unit testing interceptor with custom header

I've been trying to run a test unit in an interceptor for Angular 6, however after much trial and error I keep getting the following error: 我一直在尝试在Angular 6的拦截器中运行测试单元,但是经过反复尝试,我仍然收到以下错误:

Error: Expected one matching request for criteria "Match by function: ", found none. 错误:预期对标准“按功能匹配:”的一个匹配请求,但未找到。

I'm kinda new to NG6 and unit testing on it, and couldn't find anything in the documentation 我是NG6和单元测试的新手,在文档中找不到任何内容

This is what I got: 这就是我得到的:

Token Service (It's mocked since it has no connection with the backend) 令牌服务(由于与后端没有连接而被嘲笑)

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

Rest interceptor 休息拦截器

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

rest interceptor spec 其余拦截器规格

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

Can anyone help me understand what am I missing? 谁能帮助我了解我在想什么?

I think you missed the fact that TokenService is not simple value but rather class with findTokenData method which returns Observable. 我认为您错过了TokenService不是简单值而是具有返回Observable的findTokenData方法的类的findTokenData

Here's what happens: 这是发生了什么:

You defined mock: 您定义了模拟:

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

Overrided it: 覆盖它:

{
  provide: TokenService,
  useValue: mockTokenService
},

Now Angular will use this mockTokenService object as the value injected in RestInterceptor and... 现在,Angular将使用这个mockTokenService对象作为RestInterceptor注入的值,并...

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

So here is what you can do to fix that: 因此,您可以执行以下操作来解决此问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM