Unit testing 如何使用Jest测试文件下载?
我有一些代码如下:Unit testing 如何使用Jest测试文件下载?,unit-testing,jestjs,filesaver.js,Unit Testing,Jestjs,Filesaver.js,我有一些代码如下: /* global document */ /* global window */ /* global Blob */ import FileSaver from 'file-saver'; export const createDownloadFromBlob = (blob, filename, extension) => { FileSaver.saveAs(blob, `${filename}.${extension}`); }; export con
/* 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对这两种方法进行单元测试,但我不知道从哪里开始。任何帮助都将不胜感激。我将用间谍模拟
文件保存程序:
import FileSaver from 'file-saver';
jest.mock('file-saver', ()=>({saveAs: jest.fn()}))
由于你无法比较斑点,我也会嘲笑这一点:
global.Blob = function (content, options){return ({content, options})}
现在您可以像这样运行测试并使用expect
createDownload('content', 'filename', 'extension')
expect(FileSaver.saveAs).toHaveBeenCalledWith(
{content:'content', options: { type: 'application/octet-stream' }},
'filename.extension'
)
在类型脚本中:如果使用ArrayBuffer或二进制数据创建Blob,则需要单独处理该大小写而不是字符串
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};
};
谢谢你的帮助!