Say I want to test a module that returns a Promise
:
function myFunc () {
return Promise.resolve({
anArray: [1,2,3,4,5,6]
})
}
Using Jest, how can I assert the length of the array contained in the object the promise resolves to?
describe('myFunc', () => {
it('returns array of length 6', () => {
expect.assertions(1)
return expect(myFunc()).resolves // ... something here
})
})
If it were synchronous, I would do something like:
let result = myFunc()
expect(result.anArray.length).toBe(6)
How does this work with Promises?
There are two ways either return the promise from the test and make the assertion in the then
or make your test using async/await
describe('myFunc', () => {
it('returns array of length 6', () => {
expect.assertions(1)
return expect(myFunc())
.then(result => expect(result).toEqual([1,2,3,4,5,6]);)
})
})
describe('myFunc',() => {
it('returns array of length 6', async() => {
const result = await expect(myFunc())
expect(result).toEqual([1,2,3,4,5,6]);)
})
})
The docs on this topic