Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jest to test file download?

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.

like image 793
zhuhan Avatar asked Jun 21 '17 20:06

zhuhan


People also ask

How do I run a Jest test file?

In order to run a specific test, you'll need to use the jest command. npm test will not work. To access jest directly on the command line, install it via npm i -g jest-cli or yarn global add jest-cli . Then simply run your specific test with jest bar.

How do I upload a mock file to Jest?

You need to mock . text() method of File . Just add the mocked . text() method to the File.

What is Jest used to test?

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!


1 Answers

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'
)
like image 114
Andreas Köberle Avatar answered Oct 28 '22 05:10

Andreas Köberle