Jest 单元测试调用返回 Promise 的函数的函数

Ars*_*riq 5 javascript unit-testing reactjs jestjs

我有一个函数调用一个返回 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)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

而且func2,被称作func1是这样的:

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}`
    })
  })
}
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试编写一些单元测试,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)
    })
  })
Run Code Online (Sandbox Code Playgroud)

现在第一个测试通过,但第二个测试我得到Expected mock function to have been called one time, but it was called zero times.. 我不确定如何正确测试。任何形式的帮助都是可观的。

Ars*_*riq 2

好的,我已经成功了。

首先,我们需要模拟data-url-generator(这是我们导入的地方func2)。该html2pdf库在测试环境中无法工作,因为它使用了一个没有完全实现画布图形的假 DOM。

jest.mock('./data-url-generator', () => jest.fn())
Run Code Online (Sandbox Code Playgroud)

那么测试本身可以这样写:

it('invokes the `onShareFile` prop', done => {
    // given
    const t = key => `[${key}]`
    const urlMock = 'data:application/pdf;base64,PGh0bWw+PGJvZHk+PGRpdj5oZWxsbyB3b3JsZDwvZGl2PjwvYm9keT48L2h0bWw+'
    const shareFileTitle = 'bar'
    const contentRef = document.createElement('div')
    contentRef.textContent = 'hello world'
    const trackOnShareFile = () => { }
    const eventMock = {
      preventDefault: () => { },
    }
    func2.mockResolvedValue(urlMock)
    const onShareFileMock = ({ title, type, url }) => {
      // then
      expect(func2).toHaveBeenCalledTimes(1)
      expect(func2).toHaveBeenCalledWith(contentRef)
      expect(title).toBe('[shareFileTitle]')
      expect(type).toBe('application/pdf')
      expect(url).toBe(urlMock)
      done()
    }
    // when
    func1({
      contentRef,
      onShareFile: onShareFileMock,
      shareFileTitle,
      t,
      trackOnShareFile,
    })(eventMock)
  })
Run Code Online (Sandbox Code Playgroud)