So I\'ve just started to write tests for my in-progress javascript app, using sinon.js
& jasmine.js
. Works pretty well overall, but I need to also
I started out using ggozad's solution of spying on _updateHash
which partially worked for me. However, I discovered that my tests were confused because the hash never updated, so code that relied upon calls to getHash
or getFragment
were failing.
What I ended up with is the following helper function that spies on both _updateHash
and getHash
. The former records the request to update the hash, and the latter returns the last hash that was passed to _updateHash
. I call this helper function in my tests before I start the Backbone history.
/**
* Prevent Backbone tests from changing the browser's URL.
*
* This function modifies Backbone so that tests can navigate
* without modifying the browser's URL. It works be adding
* stub versions of Backbone's hash functions so that updating
* the hash doesn't change the URL but instead updates a
* local object. The router's callbacks are still invoked
* so that to the test it appears that navigation is behaving
* as expected.
*
* Note: it is important that tests don't update the browser's
* URL because subsequent tests could find themselves in an
* unexpected navigation state.
*/
preventBackboneChangingUrl = function() {
var history = {
currentFragment: ''
};
// Stub out the Backbone router so that the browser doesn't actually navigate
spyOn(Backbone.history, '_updateHash').andCallFake(function (location, fragment, replace) {
history.currentFragment = fragment;
});
// Stub out getHash so that Backbone thinks that the browser has navigated
spyOn(Backbone.history, 'getHash').andCallFake(function () {
return history.currentFragment;
});
};