Bry*_*her 4 backbone.js jasmine
我试图测试单击一个元素时,调用一个函数.它似乎很容易,但我必须错过一些愚蠢的东西,因为我似乎无法让这个简单的例子起作用.
这是我的观点
(function($) {
window.LaserMonitor = {
Views: {}
};
window.LaserMonitor.Views.WorkstationSummary = Backbone.View.extend({
tagName: 'li',
className: 'StationItem',
initialize: function() {
_.bindAll(this, 'showDetails');
this.template = _.template($("#WorkstationSummary").html());
},
events: {
'click h3' : 'showDetails'
},
showDetails: function() {
},
render: function() {
var renderedTmpl = this.template(this.model.toJSON());
$(this.el).append(renderedTmpl);
return this;
}
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
这是我的茉莉花测试:
describe('WorkstationSummary Item', function() {
beforeEach(function() {
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
loadFixtures('LaserMonitorFixture.html');
this.model = new Backbone.Model({
id: 1,
name: 'D8',
assigned: 1900,
inProgress: 4,
completed: 5
});
this.view = new window.LaserMonitor.Views.WorkstationSummary({model: this.model});
});
describe('Events', function() {
beforeEach(function() {
this.view.render();
});
it('should trigger click event', function() {
this.header = this.view.$('h3');
spyOn(this.view, 'showDetails');
this.header.click();
expect(this.view.showDetails).toHaveBeenCalled();
});
});
});
Run Code Online (Sandbox Code Playgroud)
这次运行的结果是:
错误:已调用showDetails上的预期间谍.at new(http:// localhost:57708/JobMgr2/test-js/lib/jasmine-1.0.2/jasmine.js:102:32)at [object Object] .toHaveBeenCalled(http:// localhost:57708/JobMgr2/object-js/lib/jasmine-1.0.2/jasmine.js:1171:29)在[object Object].(http:// localhost:57708/JobMgr2/test-js/spec/LaserMonitorSpec.js:33:34)at [object Object] .execute(http:// localhost:57708/JobMgr2/test-js/lib/jasmine) -1.0.2/jasmine.js:1001:15)在[object Object] .next_(http:// localhost:57708/JobMgr2/test-js/lib/jasmine-1.0.2/jasmine.js:1790:31) )在http:// localhost:57708/JobMgr2/test-js/lib/jasmine-1.0.2/jasmine.js:1780:18
编辑:为completness添加fixture模板:
<script type="text/template" id="WorkstationSummary">
<h3>{{ name }} ({{ assigned }}/{{ inProgress }}/{{ completed }})</h3>
<ul>
</ul>
</script>
Run Code Online (Sandbox Code Playgroud)
如果你为方法创建一个间谍,在运行测试时,调用间谍而不是调用实际方法.间谍是该方法的包装器.但问题是你在创建间谍之前创建了视图.所以实际的方法是调用而不是间谍.您需要做的是在创建视图对象之前创建间谍.我用sinon.js监视方法.并且您必须使用视图的原型来监视该视图的方法:
var workStationSpy = sinon.spy(window.LaserMonitor.Views.WorkstationSummary.prototype, "showDetails");
this.view = new window.LaserMonitor.Views.WorkstationSummary({model: this.model});
this.view.render();
expect(workStationSpy).toHaveBeenCalled();
workStationSpy.restore();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1983 次 |
| 最近记录: |