如何使用Jest测试文件下载? [英] How to use Jest to test file download?
本文介绍了如何使用Jest测试文件下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些如下代码:
/* 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);
};
我想用Jest对这两种方法进行单元测试,但是我不知道从哪里开始.任何帮助将不胜感激.
I want to use Jest to unit-test these two methods, but I don't know where to start. Any help would be appreciated.
推荐答案
我会用间谍来模拟FileSaver
:
import FileSaver from 'file-saver';
jest.mock('file-saver', ()=>({saveAs: jest.fn()}))
由于您无法比较Blob,因此我也会对此进行嘲笑:
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'
)
这篇关于如何使用Jest测试文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文