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.
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.
You need to mock . text() method of File . Just add the mocked . text() method to the File.
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!
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'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With