使用Mocha,Chai,Sinon模拟和测试按键事件?

时间:2016-11-11 14:52:46

标签: javascript backbone.js mocha sinon chai

我有一个Backbone视图,其中包含keyupkeydown个事件的自定义事件。

events: {
    "keyup .search-box": "changeTextTimer",
    "keydown .search-box": "cancelTextTimer"
},

我正在编写单元测试来检查在keyup或keydown之后是否调用了这些回调。我使用jQuery来触发关键事件。

it("should call cancelTextTimer", function() {
    var searchBox = new SearchBoxView({el: $(HTML),}).render();

    var e = $.Event("keydown");
    e.which = 65;
    searchBox.$(".search-box").trigger(e);

    var changeTextTimer = sinon.spy(searchBox, "cancelTextTimer");
    _.defer(changeTextTimer.restore);

    changeTextTimer.should.have.been.calledOnce;

});

但是,我收到了

AssertionError: expected cancelTextTimer to have been called exactly once, but 
it was called 0 times: Got value cancelTextTimer but expected a value undefined undefined

1 个答案:

答案 0 :(得分:0)

试试这个

it("should call cancelTextTimer", function(done) {
    var searchBox = new SearchBoxView({el: $(HTML),}).render();
    var changeTextTimer = sinon.spy(searchBox, "cancelTextTimer");
    _.defer(changeTextTimer.restore);

    var e = $.Event("keydown");
    e.which = 65;
    searchBox.$(".search-box").trigger(e);

    setTimeout(() => {
        changeTextTimer.should.have.been.calledOnce;
        done();
    }, 0);

});