I am mocking a function:
jest.mock('utils/downloadData')
In utils/download data I created a mock file:
export default {
general: jest.fn(() => {
console.log('mock fired')
}),
csv: jest.fn(() => {
console.log('mock fired')
}),
}
This function is being called inside a function I am testing:
...
const convertToCsv = () => {
downloadData.csv(CSV.stringify(csvData), fileName)
onFinish()
}
...
When debugging I see that the mock function is correctly set in the closure, when debugging step by step I see that the code reaches inside the mocked function and that console logs the message. Yet this test fails:
expect(downloadData.csv).toBeCalledTimes(1)
Jest accepts downloadData.csv inside the expect so I believe it sees the mocked function.
How is it possible that it doesn't register it as being called?
The tested function involved an async data fetching, which was mocked too. But the asynchronous nature of that caused the test to evaluate expected values before it finished running the tested function.
What helped was not just making the test function asynchronous (test('output', async() => {) but also including this line above the evaluation:
await new Promise(process.nextTick)
This allows the test to finish the asynchronous bits before evaluating the results.