Search code examples
javascriptangularunit-testingjasmineangular-http-interceptors

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:

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

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?


Solution

  • I think you missed the fact that TokenService is not simple value but rather class with findTokenData method which returns Observable.

    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...

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