使用Jasmin和Sinon对Stubbing Backbone类构造函数进行拼接

时间:2015-03-31 12:50:30

标签: javascript backbone.js jasmine marionette sinon

在以下模块中:

@APP.module "LeftSidebar", (LeftSidebar, APP, Backbone, Marionette) ->

API =
  initialize: ()->
    @controller = new LeftSidebar.Controller

LeftSidebar.addInitializer ()->
  API.initialize()

...我想测试LeftSidebar.Controller在调用APP.LeftSidebar.addInitializer()时是否被初始化。我尝试使用以下规范,但@spy.calledWithNew()返回false:

describe "LeftSidebar app", ->
  describe "initialization", ->
    beforeEach ->
      @spy = sinon.spy(APP.LeftSidebar, "Controller")
      APP.LeftSidebar.addInitializer()

  it "initializes LeftSidebar.Controller", ->
    expect(@spy.calledWithNew()).toBeTruthy()

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

  1. 代替initialize间谍。
  2. 您缺少要测试的初始化,请将其添加到测试中。
  3. describe "LeftSidebar app", ->
      describe "initialization", ->
        beforeEach ->
          @spy = sinon.spy(@controller, "initialize")
          // APP.LeftSidebar.addInitializer() // this does nothing, drop it
    
      it "initializes LeftSidebar.Controller", ->
        new @controller();
        expect(@controller.initialize.calledOnce).toBeTruthy()