【发布时间】:2013-01-30 05:15:39
【问题描述】:
我正在使用 Require.js 和 Backbone.Marionette 编写一个 Backbone.js 应用程序,并使用带有 Chai、Sinon 和 Sinon-Chai 的 Mocha 对其进行测试。我一直使用Jarrod Overson's Backbone Marionette with Require.JS TODO sample 作为应用程序结构的参考,Jim Newbery's posts on testing Backbone apps 作为单元测试的参考。
我的问题是尝试测试将Marionette ItemView 添加到Marionette Application object。我认为测试是否添加了 ItemView 的最佳方法是观察其 render() 方法是否被调用。由于 Marionette 提供了默认的 render() 实现,我认为最好只使用 Sinon spy 进行 onRender() 回调。
我使用Squire.JS 为我的 ItemView 返回一个存根类,如下所示:
define(['Squire', 'backbone.marionette'], function(Squire, Marionette) {
describe('App', function() {
var testContext;
beforeEach(function(done) {
testContext = {};
testContext.injector = new Squire();
testContext.renderSpy = sinon.spy();
testContext.injector.mock('app/views/Header', function() {
var stub_template_html = "<div></div>";
var HeaderStub = Marionette.ItemView.extend({
template: function(serialized_model) {
return _.template(stub_template_html);
}
});
return HeaderStub;
});
testContext.injector.require(['app/app'], function(app) {
testContext.app = app;
done();
});
});
it ('Should add a Header view to the \'header\' region', function() {
testContext.app.start();
expect(testContext.renderSpy).to.be.called();
});
当我通过 Chrome 运行 Mocha 时,我收到了预期的错误:“expected spy to have been called at least once, but it was never called.”但是,如果我将Sinon spy函数指定为onRender()回调,如下图
var HeaderStub = Marionette.ItemView.extend({
// ...
onRender: testContext.renderSpy
});
我收到一条错误消息,指出 called() 方法不是函数。
有没有办法在类定义中将 Sinon spy 函数指定为方法?或者,是否有更好的方法来测试此代码?我对 JavaScript 还很陌生,所以这可能是一个更普遍的问题,而不是特定于 Sinon 的问题。
感谢任何帮助。
【问题讨论】:
标签: javascript mocha.js sinon