How to use Jest to test file download?

孤街醉人 提交于 2019-12-05 10:12:48

I would mock out FileSaver with a spy:

import FileSaver from 'file-saver';
jest.mock('file-saver', ()=>({saveAs: jest.fn()}))

As you cant compare Blobs I would mock this as well:

global.Blob = function (content, options){return  ({content, options})}

now you can run your test and use expect like this

createDownload('content', 'filename', 'extension')
expect(FileSaver.saveAs).toHaveBeenCalledWith(
  {content:'content', options: { type: 'application/octet-stream' }}, 
  'filename.extension'
)

In Typescript: If you create a Blob with a ArrayBuffer or binary data then you need handle that case separately than strings.

import * as CRC32 from 'crc-32';

(window as any).global.Blob = function(content, options) {
    // for xlxs blob testing just return the CRC of the ArrayBuffer
    // and not the actual content of it.
    if (typeof content[0] !== 'string') {
        content = CRC32.buf(content);
    }
    return {content: JSON.stringify(content), options};
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!