測試用例 虛擬dom下載

蛋殼君發表於2020-10-19

download.ts

const downloadWithLink = (dataUrl: string, fileName?: string): void => {
  let link = document.createElement('a') as any
  link.href = dataUrl
  link.download = fileName
  link.click()
  link = null
}

export default downloadWithLink

 

download.test.ts

import downloadWithLink from '@src/downloadWithLink'

test('下載', () => {
  const link: any = {
    click: jest.fn()
  }
  jest.spyOn(document, "createElement").mockImplementation(() => link)

  downloadWithLink('https://github.alessandropellizzari.it/test/apedesign-bg.png', 'apedesign-bg.png')

  expect(link.download).toEqual("apedesign-bg.png")
  expect(link.href).toEqual('https://github.alessandropellizzari.it/test/apedesign-bg.png')
  expect(link.click).toHaveBeenCalledTimes(1)
})

 

相關文章