Testing with Promises
Learn how to use Jest to test asynchronous code with promises.
We'll cover the following
Using promises
Promises are an alternative to using callbacks in JavaScript. They are at the core of modern JavaScript asynchronous code. A promise is an object that represents the completion of asynchronous code. Once created, the promise is pending and ultimately either moves into a state of being resolved or rejected, depending on whether or not the asynchronous code was successful.
We can chain the .then()
and .catch()
methods onto the function creating the promise. .then()
would receive the resolved promise, along with any data received from the call, and .catch()
receives it if rejected. In addition, Promise.resolve()
, Promise.rejected()
, and Promise.all()
can be used to manage the completion of a Promise
object.
Jest and the Promise
object
Thankfully, the Promise
object is an object (almost) like any other in JavaScript. That means we can work with it in the same way that we would with any other return value, including inside our testing environment. Jest allows us to make assertions directly on the returned promise, testing the completed state and associated value.
In the example below, we are again using our getCatFacts
call, but this time using promises instead of a callback function. In promises.js
, we can see we make and return the asynchronous call from our function.
Get hands-on with 1400+ tech skills courses.