How do you mock File Picker in a browser for unit testing?

I am interested in how to globally shout out the file collector in a browser. In particular, I'm most interested in this in Firefox , but would prefer a general solution.

I don’t care that you don’t see the file selection dialog. I do not need to claim that it opened. The problem is that I have unit tests for JavaScript code that open the file collector. When the dialog opens, it stops the execution of the test suite .

An example of a situation is that I am testing onRender Backbone.View method. This method displays a preview that File Picker will open when it is rendered. Since I did not directly test this view, I would prefer not to mock part of my behavior when I am only interested in unit testing any other part of the onRender method.

Example:

 //Test file it("should do something", function() { var view = new App.Views.SomeView(); spyOn(view.modelBinder, "bind"); view.render(); expect(view.modelBinder.bind).toHaveBeenCalled(); }); //View file onRender : function () { this.modelBinder.bind(this.el, this.model); this.$("#thing").html(this.subview.render().el); //This line has a side effect that opens file picker } 

In fact, I don’t want to explicitly state the behavior that causes the file collector to open, because I'm not interested in testing here. This will make the test suite much more fragile and difficult to maintain.

+6
source share
2 answers

Use sinon to mock / spy / interrupt calls. You can check the execution of calls instead of actual calls.

This way you can check if the function is called without calling the actual function that displays the dialog.

0
source

To answer your question: Just do not.

I would replace subview.render() an empty function to avoid an unwanted side effect. However you say:

"I don’t want to explicitly make fun of the behavior that causes the file collector to be opened, because that’s not what interests me when testing ..."

This is a bit controversial. If you want Unit-Test App.Views.SomeView , you will have to mock external employees, especially when it's not interesting, including your file collector. On the other hand, you should not mess with the SUT when testing the device.

Mocking will actually make your test more prone to red, but this is the only way to make sure your production code does not suffer from a bad form of coupling (IMHO, a common error with Backbone.js applications.)

The only place you will need to avoid selecting files is when you test your file picker yourself, in which case you can use sinon as sugested or leave it uncoated if you use jQuery, Remember the rule "Never scoff over a type you don’t own. "

0
source

All Articles