我创建了一个(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...
...
修改: 我删除了模拟服务,并更改了提供程序列表
...
{provide: ErrorHandler, useClass: GlobalErrorHandler},
...
spyOn(this.service, 'handleError').and.callThrough();
expect(() => this.component.methodToFail()).toThrowError();
expect(this.service.handleError).toHaveBeenCalled();
但是还是一样的错误...