【发布时间】:2020-11-30 16:45:36
【问题描述】:
我有一个函数调用一个返回 Promise 的函数。这是它的代码:
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)
}
}
}
在func1 中调用的func2 是这样的:
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}`
})
})
}
现在我正在尝试为func1 编写一些单元测试,但遇到了一些问题。到目前为止我所做的是:
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)
})
})
现在第一次测试通过,但第二次测试我得到Expected mock function to have been called one time, but it was called zero times.。我不确定如何正确测试它。任何形式的帮助都是可观的。
【问题讨论】:
-
如果第一个通过但第二个失败,这仅意味着
func2失败。如果您删除if (process.env.NODE_ENV === 'development') {并记录错误,您将看到错误。在测试期间,您的环境可能是test而不是development。
标签: javascript reactjs unit-testing jestjs