我正在使用 Require.js 和 Backbone.Marionette 编写一个 Backbone.js 应用程序,并使用带有 Chai、Sinon 和 Sinon-Chai 的 Mocha 对其进行测试。我通常使用Jarrod Overson 的 Backbone Marionette 和 Require.JS TODO 示例作为应用程序结构的参考,以及Jim Newbery 的关于测试 Backbone 应用程序的帖子作为单元测试的参考。
我的问题是尝试测试将Marionette ItemView添加到Marionette Application 对象。我想测试是否添加了 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 时,我得到了我期望的错误:“预计 spy 至少被调用过一次,但它从未被调用过。” 但是,如果我指定Sinon spy函数作为onRender()
回调,如下图
var HeaderStub = Marionette.ItemView.extend({
// ...
onRender: testContext.renderSpy
});
我收到一条错误消息,指出该called()
方法不是函数。
有没有办法将 Sinon 间谍函数指定为类定义中的方法?或者,是否有更好的方法来测试此代码?我对 JavaScript 相当陌生,所以这可能是一个更普遍的问题,而不是特定于 Sinon 的问题。
任何帮助表示赞赏。