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?
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.
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.
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.
You need to mock . text() method of File . Just add the mocked . text() method to the File.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With