我正在使用Require.js和Backbone.Marionette编写Backbone.js应用程序,并使用Mocha与Chai,Sinon和Sinon-Chai进行测试 . 我一般使用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的问题 .
任何帮助表示赞赏 .
1 回答
我不确定你正在使用什么断言库,但是为了检查你是否使用sinon监视一个函数,你必须检查 Spy 的
called
属性 . 见http://sinonjs.org/docs/#spies所以你的断言应该是这样的: