I have a function that triggers another function which returns a Promise. Below is the code snippet for reference:
export const func1 = ({
contentRef,
onShareFile,
t,
trackOnShareFile,
}) => e => {
trackOnShareFile()
try {
func2(contentRef).then(url => {
onShareFile({
title: t('shareFileTitle'),
type: 'application/pdf',
url,
})
}).catch(e => {
if (process.env.NODE_ENV === 'development') {
console.error(e)
}
})
e.preventDefault()
} catch (e) {
if (process.env.NODE_ENV === 'development') {
console.error(e)
}
}
}
The function func2
, called within func1
, looks something like this:
const func2 = element => {
return import('html2pdf.js').then(html2pdf => {
return html2pdf.default().set({ margin: 12 }).from(element).toPdf().output('datauristring').then(pdfAsString => {
return pdfAsString.split(',')[1]
}).then(base64String => {
return `data:application/pdf;base64,${base64String}`
})
})
}
I am currently working on writing unit tests for func1
but facing some challenges. So far, I've tried the following:
describe('#func1', () => {
it('calls `trackOnShareFile`', () => {
// given
const props = {
trackOnShareFile: jest.fn(),
onShareFile: jest.fn(),
shareFileTitle: 'foo',
contentRef: { innerHTML: '<div>hello world</div>' },
}
const eventMock = {
preventDefault: () => {},
}
// when
func1(props)(eventMock)
// then
expect(props.trackOnShareFile).toBeCalledTimes(1)
})
it('calls `onShareFile` prop', () => {
// given
const props = {
trackOnShareFile: jest.fn(),
onShareFile: jest.fn(),
shareFileTitle: 'foo',
contentRef: { innerHTML: '<div>hello world</div>' },
}
const eventMock = {
preventDefault: () => {},
}
// when
func1(props)(eventMock)
// then
expect(props.onShareFile).toBeCalledTimes(1)
})
})
While the first test passes successfully, the second one throws an error stating
Expected mock function to have been called one time, but it was called zero times.
. I'm seeking guidance on how to correctly write this test. Any assistance would be greatly appreciated.