测试Javascript文件下载实用功能

问题描述

我编写了实用函数来下载以路径为输入的文件并根据路径下载文件名。这是:

static downloadFile(path) {
  return fetch(path)
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    const fileName = path.includes('file1') ? 'file.csv' : 'file2.csv';
    a.setAttribute('download',fileName);
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  })
 }

下面是我的测试功能不起作用。帮我找出我在这里做错了什么?

function jsonOk (body) {
  var mockResponse = new window.Response(JSON.stringify(body),{
    status: 200,headers: {
      'Content-type': 'application/json','Accept': 'text/csv'
    }
  });

  return Promise.resolve(mockResponse);
}

const MOCK_JSON = {
  'key1' : 'value1'
};

describe('Test utils',() => {
  beforeEach(() => {
      let stub = sinon.stub(window,'fetch');
      stub.onCall(0).returns(jsonOk(MOCK_JSON));
   });
  afterEach(() => {
      window.fetch.restore();
   });
  it('test csv download',() => {
    const link = {click: sinon.spy();}
    global.URL.createObjectURL = sinon.fake.returns('https://something.com');
    global.URL.revokeObjectURL = sinon.fake();
    global.Blob = function(content,options) {
       return {content,options};
     };
    sinon.Spy(document,'createElement',() => link);
    // my actual fn call
    Utils.downloadFile('https://something.com/file1');
    expect(link.download).to.equal('file1.csv'); // Chai check
    expect(link.click).should.have.callCount(1);
  });
});

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...