16

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.

2 Answers 2

35

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' ) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help!
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}; }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.