This article is about fixing
  • 08-Feb-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing

“DeprecationWarning: Unhandled promise rejections are deprecated” in Facebook Jest

Lightrun Team
Lightrun Team
08-Feb-2023

Explanation of the problem

The following technical description outlines an issue encountered while testing a Node.js application with Jest version 22.0.6. A test is performed on an asynchronous function and produces a log indicating an “UnhandledPromiseRejectionWarning” and a “DeprecationWarning”. The first warning is being discussed in a separate GitHub issue (https://github.com/facebook/jest/issues/3251) as a feature request for configurable logging. However, the second warning regarding the deprecation of unhandled promise rejections is causing concern, as it suggests that future versions of Node.js may terminate the process with a non-zero exit code. The author is seeking clarification on the potential impact on their test suite and whether there is anything that Jest should be doing to prevent future crashes. The author is using Node.js version 8.9.1 on macOS Sierra.

The code for the test being performed and the log produced are included below:

test("I'm asynchronous", async () => {
  const promise = Promise.reject("boom!")
  expect("some precondition").toBeFalsy()
  await rejected(promise)
  expect("some postcondition").toBeTruthy()
})

async function rejected(promise) {
  try {
      await promise
  } catch (e) {
      return e
  }
  throw new Error('Expected promise to be rejected')
}
(node:33041) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): boom!
(node:33041) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
 FAIL  ./test.js
  ✕ I'm asynchronous (6ms)

  ● I'm asynchronous

    expect(received).toBeFalsy()
    
    Expected value to be falsy, instead received
      "some precondition"

      2 |   const promise = Promise.reject("boom!")
      3 | 
    > 4 |   expect("some precondition").toBeFalsy()
      5 | 
      6 |   await rejected(promise)
      7 | 
      
      at Object.<anonymous>.test (test.js:4:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.759s
Ran all test suites.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for “DeprecationWarning: Unhandled promise rejections are deprecated” in Facebook Jest

The “DeprecationWarning: Unhandled promise rejections are deprecated” warning message in Facebook Jest is related to the handling of promise rejections in Node.js. This warning indicates that the current behavior of not handling rejected promises will change in future Node.js releases, and that these unhandled rejections may cause the Node.js process to terminate with a non-zero exit code.

To address this issue, it is recommended to handle promise rejections appropriately within your test code. This can be achieved by using a try-catch block, as demonstrated in the following example:

try {
  await promise
} catch (e) {
  // handle the rejection here
}

Alternatively, you can use the .catch() method to attach an error handler to the promise, as shown in the following example:

promise.catch(e => {
  // handle the rejection here
})

Handling promise rejections in this manner will ensure that your test code is compatible with future Node.js releases, and will prevent the Node.js process from terminating with a non-zero exit code.

Other popular problems with Facebook Jest

Problem: Incorrect Configuration

One of the most common issues faced by users of Facebook Jest is incorrect configuration. This can lead to various test failures, such as unexpected behavior, test timeouts, and other issues. To resolve this problem, it is important to properly configure Jest according to your needs.

Solution:

To resolve this issue, check the Jest configuration in your package.json file or jest.config.js file, and ensure that it is correctly set up to meet your testing requirements. You can also refer to the Jest documentation for more information on how to configure Jest correctly.

Problem: Asynchronous Testing

Another common issue faced by users of Facebook Jest is the handling of asynchronous code in tests. This can lead to test timeouts, unexpected test results, and other issues.

Solution:

To resolve this issue, use Jest’s asynchronous testing functionality, such as the async and await keywords, or the .then() and .catch() methods. Additionally, you can use Jest’s done callback to indicate when an asynchronous test is complete. Proper use of Jest’s asynchronous testing functionality will ensure that your tests run smoothly and produce accurate results.

Problem: Unhandled Promise Rejections

Another common issue faced by users of Facebook Jest is the handling of promise rejections. This can lead to deprecation warnings and potential termination of the Node.js process with a non-zero exit code.

Solution:

To resolve this issue, handle promise rejections appropriately within your test code. This can be achieved by using a try-catch block, as demonstrated in the following example:

try {
  await promise
} catch (e) {
  // handle the rejection here
}

Alternatively, you can use the .catch() method to attach an error handler to the promise, as shown in the following example:

promise.catch(e => {
  // handle the rejection here
})

Handling promise rejections in this manner will ensure that your test code is compatible with future Node.js releases, and will prevent the Node.js process from terminating with a non-zero exit code.

A brief introduction to Facebook Jest

Facebook Jest is a JavaScript testing framework developed and maintained by Facebook. It is a popular choice among developers due to its speed, simplicity, and feature-rich nature. Jest provides a complete testing solution for JavaScript projects, with built-in support for assertion libraries, mocking, code coverage, and more.

Jest utilizes a custom, flexible, and efficient test runner that makes it easy to run tests in parallel and provides detailed results and feedback. It also supports various testing styles, including unit testing, integration testing, and end-to-end testing. With its intuitive and easy-to-read syntax, Jest makes it simple for developers to write, maintain, and run tests, making it an ideal choice for teams looking to build high-quality applications with confidence.

Most popular use cases for Facebook Jest

  1. Unit Testing: Facebook Jest can be used to write and run unit tests for individual functions or modules. Jest makes it easy to write tests and provides a simple syntax for asserting the expected output. For example, consider the following code block for testing a simple math function:
// math.js
export function add(a, b) {
  return a + b;
}

// math.test.js
import { add } from './math';

test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});
  1. Snapshot Testing: Jest also provides a feature called snapshot testing, which allows developers to automatically capture and compare the output of a component or function. If the output changes, the test will fail, and the developer will be notified of the difference. This helps ensure that components and functions behave consistently over time and makes it easier to identify and fix unintended changes.
  2. End-to-End Testing: Jest can also be used for end-to-end testing, where the focus is on testing the complete system, including all its dependencies, and ensuring that it works as expected. Jest provides a simple syntax for writing end-to-end tests, making it easy for developers to test their applications from top to bottom. This helps catch any integration or system-level issues before they make their way into production.
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.