使用Jasmine监视Backbone.js路由调用

eld*_*all 9 javascript coffeescript backbone.js jasmine

在Backbone Router上监视方法调用时遇到问题,以确保它在给定路由上调用正确的方法.

从测试中摘录

describe 'Router', ->
    beforeEach ->
        @router = new App.Router()
        Backbone.history.start()

    afterEach ->
        Backbone.history.stop()

    describe 'routes', ->
         it 'should be defined', ->
              expect(@router.routes).toBeDefined()

         describe 'default route', ->
             it 'should be defined', ->
                  expect(@router.routes['']).toBeDefined()

             it 'should call index', ->
                 spy = spyOn(@router, "index")
                 @router.navigate('', true)
                 expect(spy).toHaveBeenCalled()
Run Code Online (Sandbox Code Playgroud)

路由器

class App.Router extends Backbone.Router
    routes:
        '' : 'index'

    index: ->
        console.log "router.index has been called"
Run Code Online (Sandbox Code Playgroud)

除了上一次测试"应该调用索引"之外,一切都通过了.它失败并显示消息"已调用预期的间谍索引".我尝试了其他变种

it "should call index", ->
    spyOn(@router, "index")
    @router.navigate('', true)
    expect(@router.index).toHaveBeenCalled()
Run Code Online (Sandbox Code Playgroud)

我还可以在原始Router.index函数的测试输出中看到"router.index已被调用"日志输出

谢谢!

编辑:一个解决方案

describe '#1 Solution', ->
    it 'should call index', ->
        spyOn(App.Router.prototype, "index")
        @router = new App.Router()
        Backbone.history.start()
        @router.navigate('', true)
        expect(App.Router.prototype.index).toHaveBeenCalled()
Run Code Online (Sandbox Code Playgroud)

fgu*_*len 15

我花了太多时间来找一个工作的jsFiddle,这个问题已经被@MarkRushakoff回答了.

我还有一些评论.

Backbone绑定路由的方式非常难以测试.

关键是路由器方法不直接在路由器实例中调用,方法被作为回调并存储在内部Backbone.history.route等待执行,检查Backbone.Router.route代码.

此操作在瞬间完成的Router,需要实例,所以你要spy你的Router.method您实例引用之前,所以你不得不推迟Backbone.history.start也在之后spy已经被激活.

由于必须spy在创建路由器实例之前声明,因此必须在类级别中执行此操作.

这么说这是我带来的最简单的解决方案:

describe("Router", function() {
  afterEach( function(){
    Backbone.history.stop();
  });

  it("should call index", function(){
    spyOn(App.Router.prototype, "index")
    var router = new App.Router(); // instance created after spy activation
    Backbone.history.start();      // it has to start after the Router instance is created

    router.navigate('', true);

    expect(App.Router.prototype.index).toHaveBeenCalled();  
  });
});
Run Code Online (Sandbox Code Playgroud)

结论,我认为Backbone.Router实现没有直观的设计.