骨干&茉莉花间谍:监视特定模型的触发器调用

时间:2013-11-06 13:59:06

标签: javascript jquery backbone.js jasmine

我正在尝试编写一个监听骨干模型事件触发器的茉莉花间谍。间谍在某种程度上起作用:它会在每次model.trigger电话上进行间谍活动。有没有办法让我只能找到特定的电话?

例如,如果我想监视@trigger 'error',而不是@trigger 'change',我可以这样做吗?在下面的模型中,@set调用还会触发Backbone change事件,该事件触发了我的触发间谍并导致测试失败。

骨干模型定义:

class @AdminDatasetModel extends Backbone.Model
  toggleEnabled: ->
    @set 'enabled', !@get('enabled')
    $.ajax
      url: "#{@urlRoot}/#{@get('id')}/enable"
      type: 'POST'
      data: 
        enabled: @get 'enabled'
      success: (data) =>
        PDLS.vent.trigger 'admin:itemToggled', @
      error: (jqXHR) =>
        @trigger 'error', 'There was a problem updating your dataset!'

Jasmine规范定义:

describe 'An admin dataset model', ->
    MOCK_GET_DATA =
        id: 1
        name: 'someName'
        enabled: true
        permissions:
            userId: 2

    MOCK_SUCCESS_DATA =
        succes: true

    MOCK_ERROR_DATA =
        error: true

    dataset = null

    beforeEach ->
        PDLS = new PDLSApp
        # Always return true for ajax requests, unless we specify otherwise
        spyOn($, 'ajax').andCallFake (params) ->
            params.success = MOCK_SUCCESS_DATA

        @triggerSpy = spyOn AdminDatasetModel.prototype, 'trigger'

        it 'should bubble up an error when appropriate', ->
            $.ajax.isSpy = false
            spyOn($, 'ajax').andCallFake (params) ->
                params.error MOCK_ERROR_DATA

            toggleSpy = spyOn AdminDatasetModel.prototype, 'toggleEnabled'
            dataset = new AdminDatasetModel(MOCK_GET_DATA)
            dataset.toggleEnabled()

            expect(toggleSpy).toHaveBeenCalled()
            expect(@triggerSpy).toHaveBeenCalledWith 'error', 'There was a problem updating your dataset!'

1 个答案:

答案 0 :(得分:0)

我通常喜欢做类似的事情:

listener = jasmine.createSpy 'listener'
model = new AdminDatasetModel(MOCK_GET_DATA)
model.on 'error', listener
model.toggleEnabled()
expect(listener).toHaveBeenCalledWith 'There was a problem updating your dataset!'

而不是直接在trigger

上进行间谍活动