Angular 2 - 单元测试:如何期望从组件中抛出新错误("error")
Angular 2 -Unit Test: How to expect throw new Error("error") from component
我正在为 angular 2 编写单元测试 by jasmine + karma。
我有组件检查异常并抛出错误。并编写单元测试来检查这种情况。
但是我在触发 fixture.detectChanges();
时看到一条错误消息
'Unhandled Promise rejection:'
我该如何解决这个问题。
请参阅下面的我的代码。谢谢
**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
});
})
试试这个:
expect(() => fixture.detectChanges())
.toThrowError(TypeError /*or another error type\*/);
我正在为 angular 2 编写单元测试 by jasmine + karma。
我有组件检查异常并抛出错误。并编写单元测试来检查这种情况。
但是我在触发 fixture.detectChanges();
'Unhandled Promise rejection:'
我该如何解决这个问题。 请参阅下面的我的代码。谢谢
**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
});
})
试试这个:
expect(() => fixture.detectChanges())
.toThrowError(TypeError /*or another error type\*/);