πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Property Wait in Jest for Async Code to Finish

How to Property Wait in Jest for Async Code to Finish

Ferenc Almasi β€’ 2022 July 14 β€’ Read time 2 min read
  • twitter
  • facebook

If you need to wait in Jest for x seconds, you likely want to make your test pass that depends on asynchronicity. You should never wait for a fixed time in your tests as they are making your tests non-deterministic, and also increases the time it takes to run your test suite by a fixed amount. Instead, you can do one of the following.


Returning a Promise from the test

Jest is capable of waiting for promises to be resolved or rejected if you return them from your test case. Be warned that if the promise is rejected, the test will fail. You can then write your expect statements inside the then callback like so:

Copied to clipboard! Playground
it('Should test async code', () => {
    return fetch().then(response => {
        expect(response).toBe('Resolved!')
    })
})
Return a Promise from a test in order to test it

Using async/await

You can also use the async/await keyword to simplify your code. Here, you don't need a then callback, but make sure you make your callback function async in order to use the await keyword inside it.

Copied to clipboard! Playground
it('Should test async code', async () => {
  const response = await fetch()

  expect(response).toBe('Resolved!')
})

You can also test rejects by introducing a try-catch block and writing your expect statements into your catch block. This way, you can test failures without actually making your tests fail.

Copied to clipboard! Playground
it('Should test rejections', async () => {
    try {
        await fetch()
    } catch (error) {
        expect(error).toBe('Error!')
    }
})
Looking to improve your skills? Master Jest from start to finish.
Master Jestinfo Remove ads

Expecting resolves and rejections

It's also possible to test what is the resolved or rejected values of a promise. For this, you can call either resolves or rejects on expect, where a promise is passed.

Copied to clipboard!
it('Should test the resolved and rejected value', async () => {
  await expect(fetch()).resolves.toBe('Resolved!')
  await expect(fetch()).rejects.toMatch('Error!')
})
Testing resolved and rejected values in Jest

Mocking Promises

Lastly, you can also mock promises in Jest to ensure they return with a given value. For this, you can use mockResolvedValue or mockResolvedValueOnce. Want to know what is the difference between the two? Check out the following webtip:

How to Correctly Mock Promises in Jest
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.