1

I have a Backbone.Router based myRouter, that calls certain set() methods based on the URL:

var MyRouter = Backbone.Router.extend({
  routes: {
    "doSomething/:value":                 "doSetterOnModel",   
  },

  doSetterOnModel: function(value) {
    // does some set(value) calls on my Model
  },
});

I would like to test now if with the model gets updated (set()) correctly using a QUnit test:

test( "update Model via URL change", function() {
      var value = "newValue";
      var url = "http://localhost/#/doSomething/" + value;

      //does not work as it moves page away from QUnit's tests.html page      
      window.location = url;

      // does also not work because it moves away from QUnit's tests.html page
      myRouter.navigate(url);

      deepEqual( myModel.get(key), value, "Value on Model was not updated by URL change");          
});

How can I set the URL in Qunit in order to test if my Router performs the right action for a certain URL?

nachtigall
  • 2,447
  • 2
  • 27
  • 35

1 Answers1

3

When I want to test my routers I usually bypass the document navigation altogether and simply call Backbone.history.loadUrl, which is responsible for matching URL fragments to a router methods:

Backbone.history.loadUrl("#/doSomething");

The additional benefit here is that you don't need to call Backbone.history.start in your test code. Note also the use or a relative url. Specifying the http://localhost part is not necessary.

Tiny demo here.

jevakallio
  • 35,324
  • 3
  • 105
  • 112