πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Correctly Mock Promises in Jest

How to Correctly Mock Promises in Jest

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

When working with JavaScript, you may often find yourself dealing with asynchronous code. In order to mock asynchronous code in Jest, more specifically Promises, you can use the mockResolvedValue function.

Copied to clipboard! Playground
// Mocking an imported Promise-based function with mockResolvedValue
import * as utils from '@utils'

utils.fetch = jest.fn().mockResolvedValue(42)

describe('Promises', () => {
    it('Should mock a promise', async () => {
       await expect(utils.fetch()).resolves.toBe(42)
       await expect(utils.fetch()).rejects.toMatch('Error')
    })
})

This will mock the return value of the Promise to be 42. In order to test a Promise in Jest, you need to turn your it block into async in order to use the await keyword in front of an expect statement.

Notice that you can chain either resolves or rejects off of a Promise in Jest to test both successful and failed calls. Using mockResolvedValue is equivalent to using mockImplementation with a Promise:

Copied to clipboard!
utils.fetch = jest.fn().mockImplementation(() => Promise.resolve(42))
Using mockResolvedValue is a shorthand for the above

Mocking consecutive Promises in Jest

We also have the option to mock consecutive Promise calls differently. This can be achieved by using the mockResolvedValueOnce call multiple times.

Copied to clipboard! Playground
describe('Promises', () => {
    it('Should mock each promise call differently', async () => {
        utils.fetch = jest.fn()
            .mockResolvedValue(42)    // For default mocks
            .mockResolvedValueOnce(2) // For the first call
            .mockResolvedValueOnce(3) // For the second call

        await expect(utils.fetch()).resolves.toBe(2)
        await expect(utils.fetch()).resolves.toBe(3)
        await expect(utils.fetch()).resolves.toBe(42)
    })
})

In the above example, the first two calls will have different resolved values. The first call will be resolved to 2, while the second call will be resolved to 3. Every other call will be resolved to 42. You can chain as many calls after each other as needed. This way, you can mock different calls to different values, while using mockResolvedValue, you can specify a default mock value.

  • 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.