Skip to content

Instantly share code, notes, and snippets.

@mdoel
Created September 7, 2011 18:51
Show Gist options
  • Save mdoel/1201379 to your computer and use it in GitHub Desktop.
Save mdoel/1201379 to your computer and use it in GitHub Desktop.
How to unit test this
/* How does one unit test this? */
$(document).ready(function() {
$('#map-searchform .searchform-fields label').inFieldLabels();
$('#map-search-form').submit(function (e) {
e.preventDefault();
$('#map').map_control().find($('#map-search-terms').val());
});
});
@mdoel
Copy link
Author

mdoel commented Sep 7, 2011

Note that I'm not trying to find out how to test inFieldLabels, but how to unit test the fact that it is invoked on the element of the page. Is this really only worth testing via an integration test?

@zspencer
Copy link

I would recommend using a view system like backbone so that you can test the individual bits of functionality.

I see about 7 different responsibilities being done in this one chunk of code

  1. Setting a function to be called on dom ready
  2. handling the map search forms submit event
  3. Assigning a handler for the map search forms submit event
  4. retrieving data from the map-search-terms field

There also feels like a smidge of inappropriate intimacy. $('#map').map_control().find() means that this on load method (which should probably be named instead of anonymous) has to know about the inner workings of whatever it is map_control returns, which becomes a law of demeter violation.

All this to say, the issue isn't a difficulty in testing JQuery, but our 'normal' method of writing javascript is so opposed to good design practices that it winds up being very difficult to test.

I test drove a refactoring of your code, see here: https://gist.github.com/1216413

This is testing in absolute isolation, using spys and what not with jasmine.

This also revealed a weakness in jasmine (or my understanding of jasmine) where it doesn't seem possible to assert upon what a spy method was called on...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment