DAG
DAG

Reputation: 2630

Angular unit testing promise reject without a catch

We have the following test:

"should not call 'getCustomers' when 'getAvailableYears' throws"

This used to work if we had the catch in our getAvailableYears, but now we don't need the catch anymore as we have a global error handling.

This is how getAvailableYears looks like:

this.service.getAvailableYears().then((availableYears) => {
    this.years = availableYears;
    this.loadCustomers();
});

That is the test, which used to work when we have the catch:

it("should not call 'getCustomers' when 'getAvailableYears' throws", fakeAsync(() => {
    // Arrange
    getAvailableYearsSpy = spyOn(service, "getAvailableYears").and.returnValue(Promise.reject("reason"));
    getCustomersSpy = spyOn(service, "getCustomers").and.returnValue(Promise.resolve(createCustomersTestData()));

    // Act
    fixture.detectChanges();

    tick();

    // Assert
    expect(getCustomersSpy).not.toHaveBeenCalled();
}));

Now I get the following error:

Error: Uncaught (in promise): reason

How do I work with reject in case I don't have a catch? How do I test that something cannot be called if a promise has been rejected?

Upvotes: 1

Views: 978

Answers (1)

Karsten
Karsten

Reputation: 389

If the Promise-Rejection isn't catched, it will bubble up and throw the error. So maybe you should add an expectation for the error like
expect(getAvailableYearsSpy).toThrow();

Upvotes: 1

Related Questions