I have a javascript application where users can search for locations that are then displayed on a map. The search for locations is done with AJAX calls to a server application. There is one component responsible for this server communication (searchComponent) and I want to unit test if the communication works.
Description of the custom events
My custom events are a simple Publish/Subscribe implementation taken from http://api.jquery.com/jQuery.Callbacks/:
var topics = {};
jQuery.Topic = function( id ) {
var callbacks,
method,
topic = id && topics[ id ];
if ( !topic ) {
callbacks = jQuery.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if ( id ) {
topics[ id ] = topic;
}
}
return topic;
};
The most important methods are
EVENT.publish(data)
Triggers an event and passes data to all subscribers.EVENT.subscribe(callback)
Subscribe the callback function to an EVENT: whenever the EVENT is triggered the callback function is executed.
Use case
The basic workflow is this:
- user clicks search-button
- the application calls
searchComponent.doSearch()
searchComponent.doSearch()
sends request to server- server responds
- searchComponent triggers a custom event for either
SEARCH_RESULT
orSEARCH_FAILED
- the application listens to both events and continues from there (show things on the map or produce an error message)
SEARCH_RESULT
and SEARCH_FAILED
are custom events as described above.
var SEARCH_RESULT = jQuery.Topic('SEARCH_RESULT');
var SEARCH_FAILED = jQuery.Topic('SEARCH_FAILED');
What do I want to do?
I want to test if the searchComponent is working:
- Are requests to the server being made correctly?
- Are the responses from the server handled correctly?
- Does the search fail when I make an invalid call?
- What about timeouts when the server is down?
The usual stuff. ;)
the question (finally ;))
How can I test this use case?
(preferrably using js-test-driver though I'm open for any suggestions on other javascript testing frameworks)