问题描述
我编写了实用函数来下载以路径为输入的文件并根据路径下载文件名。这是:
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 (将#修改为@)