【问题标题】:How to use Jest to test file download?如何使用 Jest 测试文件下载?
【发布时间】:2017-11-24 22:43:21
【问题描述】:

我有一些代码如下:

/* 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 对这两种方法进行单元测试,但我不知道从哪里开始。任何帮助将不胜感激。

【问题讨论】:

    标签: unit-testing jestjs filesaver.js


    【解决方案1】:

    我会用间谍嘲笑FileSaver

    import FileSaver from 'file-saver';
    jest.mock('file-saver', ()=>({saveAs: jest.fn()}))
    

    由于您无法比较 Blob,因此我也将对此进行模拟:

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

    【讨论】:

    • 感谢您的帮助!
    【解决方案2】:

    Typescript 中:如果您使用 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};
    };
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 1970-01-01
      • 2011-11-21
      • 2018-12-16
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2020-09-14
      • 2020-08-24
      相关资源
      最近更新 更多