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