question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Jest does not allow asynchronous catching of rejected promises

See original GitHub issue

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 https://github.com/facebook/jest/issues/3251)

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:7
  • Comments:11

github_iconTop GitHub Comments

10reactions
DanielSWolfcommented, Dec 20, 2019

Nice idea! I reworked it into a defuse function:

function defuse(promise) {
  promise.catch(() => {});
  return promise;
}

it('terminates the test prematurely', async () => {
  const promise = defuse(new Promise((resolve, reject) => setTimeout(() => reject(new Error('Oops')), 0)));
  await new Promise(resolve => setTimeout(resolve, 10));
  await expect(promise).rejects.toThrow('Oops');
});

Still, this is a workaround for a problem that I believe should be fixed.

5reactions
DanielSWolfcommented, Dec 19, 2019

What’s more, the code may not even be part of the test suite, but of the system under test. Consider:

code-under-test.js

export async function codeUnderTest() {
  const promise = new Promise((resolve, reject) => setTimeout(() => reject(new Error('Oops')), 0));
  await new Promise(resolve => setTimeout(resolve, 10));
  return promise;
}

test.js

import { codeUnderTest } from '../src/code-under-test.js';

describe('codeUnderTest', () => {
  it('terminates the test prematurely', async () => {
    await expect(codeUnderTest()).rejects.toThrow('Oops');
  });
});

The function codeUnderTest is perfectly valid, yet fails any unit test that attempts to call it. Is there any workaround?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing Asynchronous Code - Jest
If you expect a promise to be rejected, use the .catch method. Make sure to add expect.assertions to verify that a certain number...
Read more >
Testing promise rejection in JavaScript with Jest - Codeleak.pl
It looks like using try-catch with async/await is the easiest way to achieve this as the rejected value is thrown: it("rejects (bad)", async...
Read more >
Ignore a rejected fire-and-forget promise in jest - Stack Overflow
My function calls a private async function in a fire-and-forget manner, and does not add any error handling. Don't do that.
Read more >
Handling those unhandled promise rejections with JS async ...
by rejecting a promise which was not handled with .catch(). The solution is simple, either use .catch() as suggested by the message:
Read more >
Jest Unhandled Promise Rejection - Guide Fari
I was mocking an async function, & was testing for what would happen if that promise got rejected, ie an unsuccessful call.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found