无法测试去抖动的Backbone视图事件

Jon*_*anW 4 javascript mocha.js backbone.js underscore.js sinon

当我没有限制/去除测试通过的功能时.

然而,当我辩论该事件以防止服务器泛滥时,测试不再通过.摩卡输出AssertionError: expected execute to have been called at least once, but it was never called

应该注意的是,去抖动的呼叫在实时代码中没有错误地工作.这就是为什么我彻底搞砸了测试失败的原因.

考试:

describe('When information is entered into the search fields', function () {
    it('vents up the search:for:churches command', function () {
        var executeStub = sinon.stub(App, 'execute');

        view = new SearchForm()
        view.render();

        view.$el.find('input[name=church_name]').val('baptist')
        view.$el.find('input[name=zip]').val('61615')

        view.$el.find('input[name=zip]').trigger($.Event('keypress'))

        expect(executeStub).to.have.been.called

        view.close();
        PEP.execute.restore()
    });
});
Run Code Online (Sandbox Code Playgroud)

无节流:

var SearchForm = Backbone.Marionette.ItemView.extend({

    template: 'search_form',
    events: {
        'keypress [data-search-field]' : 'searchForChurches'
    },

    searchForChurches: function() {
        console.log('not debounced')
        var searchData = Backbone.Syphon.serialize(this);
        App.execute("search:for:churches", searchData);
    }

});
Run Code Online (Sandbox Code Playgroud)

节流:

var SearchForm = Backbone.Marionette.ItemView.extend({

    template: 'search_form',
    events: {
        'keypress [data-search-field]' : 'searchForChurches'
    },

    searchForChurches: _.debounce(function() {
        console.log('debounced')
        var searchData = Backbone.Syphon.serialize(this);
        App.execute("search:for:churches", searchData);
    }, 200)

});
Run Code Online (Sandbox Code Playgroud)

编辑: 我还发布了一个相关的后续问题:https://stackoverflow.com/questions/21167488/how-to-test-a-debounced-throttled-backbone-view-event-with-mocha-to-ensure -它是

arz*_*ezy 8

这里有一个问题,当使用UnderscoreJSSinonJS.

  • 反跳在功能UnderscoreJS使用_.now.
  • SinonJS涵盖Date对象,但不包括_.now.

出于测试目的,我在测试的bootstrap文件中替换_.now:

_.now = function() {
  return new Date().getTime();
};
Run Code Online (Sandbox Code Playgroud)


Jon*_*anW 5

西蒙的方法在大多数情况下都很有效但我不断遇到导致更多错误的不同情况.在花了更多的时间和查看sinon的文档后,我想我有更好的方法.

Sinon的假定时器来救援.

describe('When information is entered into the search fields', function () {
    it('vents up the search:for:churches command', function () {
        var clock = sinon.useFakeTimers();
        var executeStub = sinon.stub(App, 'execute');

        view = new SearchForm()
        view.render();

        view.$el.find('input[name=church_name]').val('baptist')
        view.$el.find('input[name=zip]').val('61615')

        view.$el.find('input[name=zip]').trigger($.Event('keypress'))
        clock.tick(200)

        expect(executeStub).to.have.been.called

        view.close();
        PEP.execute.restore()
        clock.restore()    
    });
});
Run Code Online (Sandbox Code Playgroud)