How to fix UnhandledPromiseRejectionWarning when testing using mocha or chai and JavaScript?

Sometimes, we want to fix UnhandledPromiseRejectionWarning when testing using mocha or chai and JavaScript.

In this article, we’ll look at how to fix UnhandledPromiseRejectionWarning when testing using mocha or chai and JavaScript.

How to fix UnhandledPromiseRejectionWarning when testing using mocha or chai and JavaScript?

To fix UnhandledPromiseRejectionWarning when testing using mocha or chai and JavaScript, we call catch to catch the rejected promise.

For instance, we write

it("should transition with the correct event", () => {
  //...
  return new Promise((resolve, reject) => {
    //...
  })
    .then((state) => {
      assert(state.action === "DONE", "should change state");
    })
    .catch((error) => {
      assert.isNotOk(error, "Promise error");
    });
});

to add a test with it.

We call catch to catch promise rejections from the promise.

And we call assert.isNotOK to check the error from the rejected promise.

Conclusion

To fix UnhandledPromiseRejectionWarning when testing using mocha or chai and JavaScript, we call catch to catch the rejected promise.