15

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.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
zhuhan
  • 193
  • 1
  • 1
  • 8

2 Answers2

33

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'
)
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
1

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};
};
David Dehghan
  • 22,159
  • 10
  • 107
  • 95