Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am interested in how to globally mock out the file picker in the browser. Specifically, I am most interested in doing this in Firefox but would prefer a general solution.

I only care about preventing the file picker dialog from appearing. I do not need to be able to assert that it did open. The problem is that I have unit tests for JavaScript code that open the file picker. When the dialog opens, it halts the execution of the test suite.

An example situation is that I am testing the onRender method of a Backbone.View. That method renders a subview, which will open the File Picker when it is rendered. Since I am not directly testing that subview, I would prefer not to mock out portions of its behavior when I am only interested in unit testing some 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
}

Essentially, I do not want to explicitly mock out the behavior that causes the file picker to be opened because it is not what I am interested in testing here. Doing so will make the test suite much more brittle and difficult to maintain.

like image 365
Andrew Hubbs Avatar asked Nov 20 '12 20:11

Andrew Hubbs


1 Answers

Use sinon to mock/spy/stub out the calls. You can test for the calls being made instead of actually making the calls.

That way you can test that the function has been called without calling the actual function that displays the dialog.

like image 50
leeand00 Avatar answered Oct 04 '22 02:10

leeand00