Faking out FormData append with Jasmine

form-data, jasmine, unit-testing

Solution

Turns out that I was wrong and the following code actually does spy correctly on the `FormData.append` method:

spyOn(FormData.prototype, "append");

The issue is that I put it too far nested in my describe blocks that other tests were failing because they also tried to call `FormData.append` and no spy was set up for those tests.

While I was working through a solution, I also realized that the following concept would work too since I don't actually care about uploading any file:

spyOn(window, 'FormData').andReturn({
    "append": jasmine.createSpy()
});

Hopefully this can help someone that needs to spy on FormData!

Problem

I need to test a unit of code that constructs a FormData object, appends a file and submits an AJAX request to the server. The issue is that I don't actually have a file object to provide to the FormData `append` method call. So I wanted to spyOn the `append` method and call a fake function of my own. Is this possible? If not, how can I test my code. The following is the unit of code I want to test: ``` var fd = new FormData(); // listOfFiles is an array of files and filename is a string var file = _.findWhere(listOfFiles, { name: filename }); fd.append("file", file, filename); $.ajax(/* options */); ``` The following is what I have for my unit test, which doesn't do the job: ``` it("does something", function() { var mockFiles = [{ name: "Test File.pdf" }]; // the addDocs call adds the files to the listOfFiles array above someView.addDocs(mockFiles); var ajaxSpy = spyOn($, "ajax"); // THIS DOESN'T WORK spyOn(FormData.prototype, "append").andReturn(false); // this event causes the above unit of code to run app.trigger('someEvent'); // do more stuff... }); ``` Right now I get the following error: ``` Failed to execute 'append' on 'FormData': No function was found that matched the signature provided ``` Which happens because my spy doesn't get called. Any help is much appreciated how to properly spy on FormData methods.

Original source