How to Correctly Mock Promises in Jest
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')
})
})
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))
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)
})
})
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.
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: