我用jasmine + karma编写角度2的单元测试
我有组件检查异常并抛出错误。并编写单元测试以检查此案例
但是在触发fixture.detectChanges();
'未处理的承诺拒绝:'
我该如何解决这个案子。 请参阅下面的代码。感谢
**MyComponent.ts**
ngOnInit() {
if (this.erorr) {
throw new Error("error");
}
}
**AppModule.ts**
class MyErrorHandler extends ErrorHandler {
handleError(error) {
console.log("error");
location.href="/error"
}
}
一个单元测试文件
**MyComponent.spec.ts**
describe('My Management Test', () => {
beforeEach(async( () => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: provider,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: imports
}).compileComponents().then(() => {});
}));
beforeEach(inject([MockBackend], (mockBackend: MockBackend) => {
Connection(mockBackend);
fixture = TestBed.createComponent(MyComponent);
}));
it('Go to contact management page', (done) => {
fixture.detectChanges();
//Need to check if component throw error
});
})
答案 0 :(得分:4)
试试这个:
expect(() => fixture.detectChanges()).toThrowError(TypeError /*or another error type*/);