使用 Jasmin 和 Sinon 存根 Backbone Class 构造函数

Stubbing Backbone Class constructor with Jasmin and 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() returns 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. 改为监视 initialize
  2. 您缺少要测试的初始化,将其添加到测试中。
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()