简体   繁体   中英

Handling reject in Promise.all in jasmine tests

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM