πŸ’‘ 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 β€’ πŸ“– 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.

// 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')
    })
})
Copied to clipboard!

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:

utils.fetch = jest.fn().mockImplementation(() => Promise.resolve(42))
Using mockResolvedValue is a shorthand for the above
Copied to clipboard!
Looking to improve your skills? Master Jest from start to finish.
Master Jest

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.

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)
    })
})
Copied to clipboard!

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.

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Courses

Recommended