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

1

9

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
    });
})
Whitley answered 14/12, 2017 at 3:41 Comment(0)
C
15

Try this:

expect(() => fixture.detectChanges())
   .toThrowError(TypeError /*or another error type\*/);
Cabrales answered 6/4, 2018 at 23:54 Comment(1)
this also works expect(() => component.ngOnInit()).toThrowError( 'MyComponent: My error message.' );Gills

© 2022 - 2024 — McMap. All rights reserved.