How to use Jest to test file download?

拥有回忆 提交于 2019-12-07 06:49:20

问题


I have some code as below:

/* global document */
/* global window */
/* global Blob */

import FileSaver from 'file-saver';

export const createDownloadFromBlob = (blob, filename, extension) => {
  FileSaver.saveAs(blob, `${filename}.${extension}`);
};

export const createDownload = (content, filename, extension) => {
  createDownloadFromBlob(new Blob([content], { type: 'application/octet-stream' }), filename, extension);
};

I want to use Jest to unit-test these two methods, but I don't know where to start. Any help would be appreciated.


回答1:


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'
)



回答2:


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};
};


来源:https://stackoverflow.com/questions/44686077/how-to-use-jest-to-test-file-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!