'Mocking a function in jest which returns Promise<string[] | never>
I'm using React+JEST to test an existing component. It has a function filterDeliveries like so :
const filterEmptyDeliveries = (arr): Promise<string[] | never> => {
if (arr.length === 0) {
return Promise.reject("empty") as any as Promise<never>
}
return Promise.resolve(arr) as Promise<string[]>
}
In my component I call it like this:
const whiteListArr = []
const setupDeliveryType = async () => {
const tempAsin = [] // Empty or Not Empty
try {
... other code
if (tempAsin.length !== 0) {
if (whiteListArr.length === 0) {
whiteListArr.push(... some list computed above)
} else {
await filterEmptyDeliveries(asinWhiteList)
}
} else {
await filterEmptyDeliveries(whiteListArr)
}
} catch (err) {
console.log(err)
} finally {
setLoading(false)
}
}
This is how I'm mocking in my tests
const filterEmptyDeliveries = jest.fn()
filterEmptyDeliveries.mockResolvedValue(['A12334567'])
it('calls setupDeliveryType ', async () => {
const wrapper = mount(<Component / >)
await act(flushPromises)
wrapper.update()
await act(flushPromises)
const whiteList = ['B00000000']
... other tests that pass so i'm pretty confident the code reaches here
await act(flushPromises)
expect(filterEmptyDeliveries).toHaveBeenCalled() // Fails
/// Fails with
Expected number of calls: >= 1
Received number of calls: 0
})
Where Am I going wrong here?
Solution 1:[1]
You are mocking a function called filterDeliveries, but the component is calling filterEmptyDeliveries.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rmths01 |