Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 -Unit Test: How to expect throw new Error("error") from component

I writing unit test for angular 2 by jasmine + karma.
I have the component check exception and throw error. And write unit test to check this case.
But I seen an error message when trigger fixture.detectChanges();

'Unhandled Promise rejection:'

How can I resolve this case. Please see the my code below. Thanks

**MyComponent.ts**

ngOnInit() {
  if (this.erorr) {
      throw new Error("error");
  }
}

**AppModule.ts**

class MyErrorHandler extends ErrorHandler {
  handleError(error) {
     console.log("error");
     location.href="/error"
  }
}

And one unit test file

**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
    });
})
like image 881
ThuyNguyen Avatar asked Dec 14 '17 03:12

ThuyNguyen


1 Answers

Try this:

expect(() => fixture.detectChanges())
   .toThrowError(TypeError /*or another error type\*/);
like image 75
dave4351 Avatar answered Sep 29 '22 00:09

dave4351