Angular 2 -Unit Test:如何期望从组件中抛出新的错误("错误")

时间:2017-12-14 03:41:09

标签: angular angular2-testing

我用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
    });
})

1 个答案:

答案 0 :(得分:4)

试试这个:

expect(() => fixture.detectChanges()).toThrowError(TypeError /*or another error type*/);