我已成功覆盖@angular/core
ErrorHandler
,但我正在尝试创建一个视图测试来断言它的行为,而我正在获取未捕获的异常。尽管在运行时工作并在TestBed提供程序中设置它,但覆盖处理程序似乎没有运行。
NG2误差-handler.ts:
import { ErrorHandler } from '@angular/core';
import { logger } from './logger';
export class Ng2ErrorHandler extends ErrorHandler {
constructor(){
super(false); // don't rethrow error
}
/* tslint:disable:no-any */
public handleError(error: any) {
super.handleError(error);
logger.handleLoggedError(error, error.message);
}
/* tslint:enable:no-any */
}
export const NG2_ERROR_HANDLER_PROVIDER = {
provide: ErrorHandler,
useClass: Ng2ErrorHandler,
};
NG2误差-handler.view.spec.ts:
import { Component } from '@angular/core';
import { NG2_ERROR_HANDLER_PROVIDER } from './ng2-error-handler';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { logger, Level } from './logger';
const ERROR_MESSAGE = 'Dummy Error';
@Component({
moduleId: module.id,
selector: 'dummy-component',
template: `<button (click)="throwError()">Throw an error</button>`
})
export class MockComponent {
public throwError(): never {
throw Error(ERROR_MESSAGE);
}
}
export function main(): void {
fdescribe('Global Error Handler', () => {
let fixture: ComponentFixture<MockComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MockComponent],
providers: [NG2_ERROR_HANDLER_PROVIDER],
});
fixture = TestBed.createComponent(MockComponent);
});
describe('Error Handler logging', () => {
let loggerSpy: jasmine.Spy;
let consoleSpy: jasmine.Spy;
let errorObservableSpy: jasmine.Spy;
beforeEach(() => {
loggerSpy = spyOn(logger, 'handleLoggedError').and.callThrough();
consoleSpy = spyOn(console, 'error');
errorObservableSpy = jasmine.createSpy('log event observable subscription');
logger.getLogEventObserver().subscribe(errorObservableSpy);
// trigger the error
fixture.nativeElement.querySelector('button').click();
});
it('should log error to the logger util', () => {
expect(loggerSpy).toHaveBeenCalledWith(jasmine.any(Error), ERROR_MESSAGE, Level.ERROR);
});
it('should log error to console', () => {
expect(consoleSpy).toHaveBeenCalled();
});
it('should have ticked the error stream which will pop error to user', () => {
expect(errorObservableSpy).toHaveBeenCalled();
});
});
});
}
所有测试均以
失败Uncaught Error: Error in dist/dev/app/shared/util/ng2-error-handler.spec.js class MockComponent - inline template:0:8 caused by: Dummy Error
at node_modules/zone.js/dist/zone.js:129