Handling reject in Promise.all in jasmine tests

655 Views Asked by At

I am trying to test a function containing a Promise.all in jasmine (TypeScript, but I assume I'd have the same problem in JS) - I want to make sure I am handling a rejection appropriately:

function foo(): Promise<void> {
    return Promise.all(promise1, promise2)
        .catch(() => undefined)
        .then(() => undefined);
}

function bar() {
    foo().finally(makeBarHappen);
}

And then my test is something like this, where I mock one of the promises inside foo to fail:

it('test bar happens even when foo fails', async () => {
     mocks.promise1.and.returnValue(Promise.reject('loremipsum'));

     pressButtonThatTriggersBar();

     await timeout(longEnoughTimeoutForBarToHappen);

     expect(barHappened);
});

The problem is, I get an "Unhandled Rejection: loremipsum thrown" error from Jasmine - even though I believe I am handling the rejection with the catch() inside of foo? I shouldn't need individual catches for every promise inside the Promise.all, should I? I tested this manually and it does catch the rejection and behave appropriately, so I'm not sure the best way to test this in Jasmine. Thanks!

1

There are 1 best solutions below

0
On

Looks like the correct way to test that promise1 failed was:

mocks.promise1.and.throwError('');

The Promise.reject() was getting caught by Jasmine before it ever had time to be caught by my actual error handling code.