api.interceptor.spec.ts 2.68 KiB
import { HttpHandler, HttpRequest } from '@angular/common/http';
import { inject, TestBed } from '@angular/core/testing';
import { AppError } from '@devatscience/ngx-errors';
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ApiInterceptor } from './api.interceptor';
import { Configuration } from '../configuration';
import { MarbleFormatter, MarbleTestScheduler } from '../testing/marbles';
describe('ApiInterceptor', () => {
  const API_BASE_URL = 'http://test.com';
  const API_PATH = '/foo/bar';
  const API_URL = `${API_BASE_URL}${API_PATH}`;
  const OTHER_URL = 'http://example.com/foo/bar';
  const RESPONSE = 'OK';
  const VALUES = {
    n: null as null,
    r: RESPONSE,
  let scheduler: MarbleTestScheduler<any>;
  let next: jasmine.SpyObj<HttpHandler>;
  let conf: Configuration;
  beforeEach(() => {
    scheduler = new MarbleTestScheduler(new MarbleFormatter(VALUES));
    next = jasmine.createSpyObj('HttpHandler', ['handle']);
    conf = new Configuration();
    conf.apiBaseURL = API_BASE_URL;
    TestBed.configureTestingModule({
      providers: [ApiInterceptor, { provide: Configuration, useValue: conf }],
    });
  });
  it('should be created', inject(
    [ApiInterceptor],
    (service: ApiInterceptor) => {
      expect(service).toBeTruthy();
  ));
  function testUrl(input: string, expected: string): void {
    const NEXT_M = /***/ '--r';
    const INTER_M = /**/ '--r';
    const req = new HttpRequest('GET', input);
    scheduler.run(({ expectObservable, cold }) => {
      next.handle.and.callFake((r: HttpRequest<any>) => {
        expect(r.url).toEqual(expected);
        return cold(NEXT_M);
      });
      inject([ApiInterceptor], (service: ApiInterceptor) =>
        expectObservable(service.intercept(req, next)).toBe(INTER_M)
      )();
    });
  it('should prepend the base URL to hostless URLs', () => testUrl(API_PATH, API_URL));
  it('should not prepend the base URL to full API URLs', () => testUrl(API_URL, API_URL));
  it('should not change other URLs', () => testUrl(OTHER_URL, OTHER_URL));
71727374757677787980818283848586878889909192
it('should classify errors', () => { const NEXT_M = /***/ '--#'; const INTER_M = /**/ '--(e|)'; const ERR_IN = new Error('Error'); (VALUES as any).e = new AppError(ERR_IN, ERR_IN.message, ERR_IN.stack, false); const req = new HttpRequest('GET', '/some/url'); scheduler .withValues(VALUES) .withError(ERR_IN) .run(({ expectObservable, cold }) => { next.handle.and.callFake(() => cold(NEXT_M)); inject([ApiInterceptor], (service: ApiInterceptor) => expectObservable(service.intercept(req, next).pipe(catchError(e => of(e)))).toBe(INTER_M) )(); }); }); });