在Backbone.Router中设置URL以进行QUnit测试

时间:2013-02-11 15:26:31

标签: backbone.js qunit backbone-routing

我有一个基于Backbone.Router的myRouter,它根据URL调用某些set()方法:

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

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

我想现在测试是否使用QUnit测试正确更新模型(set()):

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");          
});

如何设置Qunit中的URL以测试我的路由器是否对某个URL执行了正确的操作?

1 个答案:

答案 0 :(得分:3)

当我想测试我的路由器时,我通常会完全绕过文档导航,只需调用Backbone.history.loadUrl,它负责将URL片段与路由器方法匹配:

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

此处的额外好处是您无需在测试代码中调用Backbone.history.start。还要注意使用或相对URL。无需指定http://localhost部分。

Tiny demo here.