【发布时间】:2015-06-03 09:03:30
【问题描述】:
我正在为 Backbone 视图编写测试,在该视图中我通过创建 $.Event("keypress", { which: 13 }) 并将其传递给我的测试服中的 trigger 方法来模拟按键事件。但是,当我查看我的测试结果时,我看到在我的createOnEnter 函数中,这会在第一个条件下返回,并且测试失败并显示以下消息AssertionError: expected addCommentToCollection to have been called at least once, but it was never called,这意味着它没有将按键事件识别为 13。
为什么会这样? 我的设置不正确吗?
这是我要测试的主干功能:
createOnEnter: function(event) {
if (event.keyCode != 13) return;
if (!this._input.val()) return;
this.addCommentToCollection();
this.resetInputField();
this.concealButtons();
}
这是在backbone eventhash 中触发的,它监听输入字段上的按键事件。
这个问题的必要测试设置(还有许多其他的存根和间谍):
describe("AppView", function() {
before(function () {
// create test fixture
this.$fixture = $('<div id="app-view-fixture">' +
'<input id="new-comment" type="text" placeholder="what do you think?">' +
'<div class="comment-buttons">' +
'<div class="post-button"></div>' +
'<div class="cancel-button"></div>' +
'</div>' +
'<section id="main" class="comment-list">' +
'<ul class="comments-container" id="comment-list"></ul>' +
'</section></div>');
});
beforeEach(function () {
// bind the fixture for each run
this.$fixture.appendTo($("#fixtures"));
// instantiate our models
this.model1 = new Comment({
"comment": "I like cookies",
"created": "12-12-2012",
"modified": "13-01-2013",
"user": {
"username": "Mr. Knight"
}
});
this.model2 = new Comment({
"comment": "I pirate everything!",
"created": "14-09-2012",
"modified": "21-01-2013",
"user": {
"username": "Mr. Casanova"
}
});
// place models in array for use in collection instantiation
this.models = [this.model1, this.model2];
// instantiate our collection with models from above
this.collection = new CommentList(this.models,
{url: "items/1234567890/comments"}
);
this.addCommentSpy = sinon.spy(AppView.prototype, "addCommentToCollection");
this.createEnterSpy = sinon.spy(AppView.prototype, "createOnEnter");
this.resetSpy = sinon.spy(AppView.prototype, "resetInputField");
this.concealSpy = sinon.spy(AppView.prototype, "concealButtons");
// instantiate our new view
this.view = new AppView ({
"collection": this.collection,
"el": this.$fixture
});
});
afterEach(function () {
this.addCommentSpy.restore();
this.resetSpy.restore();
this.concealSpy.restore();
this.createEnterSpy.restore();
// undo our server
this.server.restore();
// destroy our view
this.view.remove();
});
after(function () {
// empty our fixtures div
$("#fixtures").empty();
});
it("should trigger createOnEnter when keypress - 'Enter' - with value in input field", function () {
this.view.$("#new-comment").val("Cousin Benson, it is broken!");
this.view.$("#new-comment").trigger($.Event("keypress", { which: 13 }));
expect(this.createEnterSpy).to.have.been.called;
expect(this.addCommentSpy).to.have.been.called;
expect(this.resetSpy).to.have.been.called;
expect(this.concealSpy).to.have.been.called;
});
});
【问题讨论】:
标签: backbone.js mocha.js keypress sinon