An Async Example
First, enable Babel support in Jest as documented in the Getting Started guide.
Let's implement a module that fetches user data from an API and returns the user name.
In the above implementation, we expect the request.js
module to return a promise. We chain a call to then
to receive the user name.
Now imagine an implementation of request.js
that goes to the network and fetches some user data:
Because we don't want to go to the network in our test, we are going to create a manual mock for our request.js
module in the __mocks__
folder (the folder is case-sensitive, __MOCKS__
will not work). It could look something like this:
Now let's write a test for our async functionality.
We call jest.mock('../request')
to tell Jest to use our manual mock. it
expects the return value to be a Promise that is going to be resolved. You can chain as many Promises as you like and call expect
at any time, as long as you return a Promise at the end.
.resolves
#
There is a less verbose way using resolves
to unwrap the value of a fulfilled promise together with any other matcher. If the promise is rejected, the assertion will fail.
async
/await
#
Writing tests using the async
/await
syntax is also possible. Here is how you'd write the same examples from before:
To enable async/await in your project, install @babel/preset-env
and enable the feature in your babel.config.js
file.
#
Error handlingErrors can be handled using the .catch
method. Make sure to add expect.assertions
to verify that a certain number of assertions are called. Otherwise a fulfilled promise would not fail the test:
.rejects
#
The.rejects
helper works like the .resolves
helper. If the promise is fulfilled, the test will automatically fail. expect.assertions(number)
is not required but recommended to verify that a certain number of assertions are called during a test. It is otherwise easy to forget to return
/await
the .resolves
assertions.
The code for this example is available at examples/async.
If you'd like to test timers, like setTimeout
, take a look at the Timer mocks documentation.