Как проверить Angular (Custom) ErrorHandler в Жасмин с TestComponent - PullRequest
0 голосов
/ 11 июня 2019

Я создал (Global) ErrorHandler, который перемещает все ошибки на страницу ошибок.

Я уже написал несколько тестов, которые работают.Но я хочу добавить следующий тест: Создать DummyComponent с методом, который выдает ошибку и ожидать, что handleError был вызван.

Так что создайте шпиона и слушайте его.Но это не работает ...

global-error-handler.service.ts

import {ErrorHandler, Injectable, Injector, NgZone} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  public constructor(private readonly _injector: Injector) {}

  public handleError() {
    const zone = this._injector.get(NgZone);
    const router = this._injector.get(Router);
    const route = this._injector.get(ActivatedRoute);

    zone.run(() => {
      router.navigate(['error-page'], {relativeTo: route});
    });
  }
}

global-error-handler.service.spec.ts

import {Component} from '@angular/core';
import {async, TestBed, ComponentFixture} from '@angular/core/testing';
import {RouterModule} from '@angular/router';

import {GlobalErrorHandler} from './global-error-handler.service';

const mockService = {
  handleError: () => {},
};

@Component({
  template: '',
})
class FailingComponent {
  public methodToFail(): void {
    throw new Error('this method fails');
  }
}

interface Ctx {
  service: GlobalErrorHandler;
  component: FailingComponent;
  fixture: ComponentFixture<FailingComponent>;
}

describe('GlobalErrorHandler', () => {
  beforeEach(async(function(this: Ctx) {
    TestBed.configureTestingModule({
      declarations: [FailingComponent],
      imports: [RouterModule],
      providers: [
        {provide: GlobalErrorHandler, useValue: mockService},
      ],
    }).compileComponents();
  }));

  beforeEach(function(this: Ctx) {
    this.fixture = TestBed.createComponent(FailingComponent);
    this.component = this.fixture.componentInstance;
    this.service = TestBed.get(GlobalErrorHandler);
  });

  it('should handleError if component throws error', function(this: Ctx) {
    spyOn(mockService, 'handleError').and.callThrough();
    expect(() => this.component.methodToFail()).toThrowError(); // This line is OK.
    expect(mockService.handleError).toHaveBeenCalled(); // this line throws error.(see below)
  });
});

вывод на консоль

GlobalErrorHandler
  ✗ should handleError if component throws error
    Expected spy handleError to have been called.
    <Jasmine>
    ./src/services/__tests__/global-error-handler.service.spec.ts...
    ...

edit: Я удалил mockService и изменил список поставщиков

...
  {provide: ErrorHandler, useClass: GlobalErrorHandler},
...
  spyOn(this.service, 'handleError').and.callThrough();
  expect(() => this.component.methodToFail()).toThrowError();
  expect(this.service.handleError).toHaveBeenCalled();

Но все равно та же ошибка ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...