如何在javascript中模拟文件

如何在javascript中模拟文件

本文介绍了如何在javascript中模拟文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一些小项目来锻炼我的TDD技能。该项目包括一个音频播放器,可以在播放列表中拖放文件。我正在使用Jasmine作为测试框架。我遇到的问题是我无法模拟javascript文件来测试我的文件上传功能。我试图像这样创建一个文件:

I'm developing some small project to exercise my TDD skills. The project consists of an audio player which has the ability to drag'n'drop files in a playlist. I'm using Jasmine as a testing framework. The problem I faced is that I can't mock javascript files to test my file upload functionality. I tried to create a File like this:

new File(new Blob(), "name");

但Chrome不允许手动创建文件。 File的构造函数是非法的。我找到了一个grunt.js的解决方案,它包含从grunt返回一些文件,但我真的不想在服务器端使用这么小的测试项目。这个问题有解决方法吗?

but Chrome does not allow creating files manually. File's constructor is illegal to use. I found a solution with grunt.js which consists of returning some files from grunt, but I don't really wanna use server-side for such a small test project. Is there any workaround for this problem?

推荐答案

Chrome会让你创建一个新文件:

Chrome will let you create a new file:

var f = new File([""], "filename", { type: 'text/html' });

但IE11(和其他浏览器?)不会。

However IE11 (and other browsers?) will not.

这是我的(可怜?)假文件:

Here's is my (poor?) fake File:

var blob = new Blob([""], { type: 'text/html' });
blob["lastModifiedDate"] = "";
blob["name"] = "filename";
var fakeF = blob;

您可以根据需要填写值。你可以用你需要的任何东西填充blob。 (请参阅其他答案,了解如何使用图像)。

You can fill in the values as you see fit. You can fill the blob with whatever you need. (See the other answer for how to use an image).

我已经在IE11,Chrome和Firefox中对此进行了测试。到目前为止,我似乎工作,至少我的单位测试目的。

I've tested this in IE11, Chrome and Firefox. So far I seems to work, at least for my unit testing purposes.

奖金:
这里是打字稿:

Bonus:Here it is in typescript:

let blob = new Blob([""], { type: 'text/html' });
blob["lastModifiedDate"] = "";
blob["name"] = "filename";

let fakeF = <File>blob;

这篇关于如何在javascript中模拟文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:17