Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock File in 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"); 

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?

like image 715
Eriendel Avatar asked Jun 30 '14 11:06

Eriendel


People also ask

How do you mock a file in Javascript?

fake File: var blob = new Blob([""], { type: 'text/html' }); blob["lastModifiedDate"] = ""; blob["name"] = "filename"; var fakeF = blob; You can fill in the values as you see fit. You can fill the blob with whatever you need.

What is mocking in Javascript?

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.

How do you mock in node JS?

In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.

How do I upload a mock file to jest?

You need to mock . text() method of File . Just add the mocked . text() method to the File.


1 Answers

Chrome will let you create a new file:

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

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; 

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

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; 
like image 72
Chris Weber Avatar answered Sep 22 '22 16:09

Chris Weber