Skip to content

Jest does not allow asynchronous catching of rejected promises #6028

Closed

Description

Bug
Jest version: 22.4.3 (But was introduced in 21.x)
Config: None (all defaults)
Node version: 6.11.5, 8.9.4

Jest does not allow you to asynchronously attach a .catch() to a promise, even if it's added before the test itself is finished. The only difference between these two tests is that the catch is added within a setTimeout() in the second one.

// This passes after ~107ms (the expected amount of time)
test('Synchronous catching of promise', (done) => {
    const promise = Promise.reject(new Error('nope'));

    promise.catch((err) => console.log('Caught error: ', err.message));
    
    // At a later time, finish the test
    setTimeout(() => {
        console.log('here');
        done();
    }, 100);
});

// This fails after ~10ms, with error message "nope"
test('Async catching of promise', (done) => {
    const promise = Promise.reject(new Error('nope'));

    setTimeout(() => {
        promise.catch((err) => console.log('Caught error: ', err.message));
    });

    // At a later time (well after the catch() has been attached to the promise), finish the test
    setTimeout(() => {
        // We nver makes it to this point because Jest sees that promise was not caught immediately
        console.log('here');
        done();
    }, 100);
});

screen shot 2018-04-18 at 4 40 26 pm

In Jest 20.x, only warnings are printed, and the test does not fail

(node:54613) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: nope
(node:54613) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 2)

(Was originally mentioned in #3251)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions