I have a function that calls a function that returns a Promise. Here is the code for it:
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)
}
}
}
And func2 that is called in func1 is 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}`
})
})
}
Now I am trying to write some unit tests for func1 but getting some issues. What I have done so far is this:
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)
})
})
Now the first test pass but for the second test I get Expected mock function to have been called one time, but it was called zero times.. I am not sure how to correctly test that. Any kind of help is appreciable.