我正在尝试使用 Jasmine 和 Sion 编写单元测试,但是在使用 RequireJs 加载模块时我很难找到以下等效项:
sinon.stub(window, "MyItemView");
使用 RequireJs 时,我无法以这种方式 stub ,因为 MyItemView 未附加到窗口。
以下是我需要 stub MyItemView 的示例:
var MyView = Backbone.View.extend({
el: '#myElement',
initialize : function() {
var that = this;
this.collection.fetch({
success : function() {
that.render();
}
});
},
render : function() {
this.collection.each(this.renderItem);
}
renderItem: function(model){
var myItemView = new MyItemView({model: model});
$('#myElement').append(myItemView.render().el);
},
...
现在,使用 Jasmine 我可以测试 innerHtml 是否包含预期的 HTML:
it('View should contain correct Html', function(){
var collectionFetchStub = sinon.stub(this.myCollection, 'fetch').yieldsTo('success', this.myCollection);
this.view = new MyView({collection: this.myCollection});
expect(this.view.el.innerHTML).toContain('<li><a href=""> 1 : test </a></li>');
// Remove Stubs
collectionFetchStub.restore();
});
但是,此测试依赖于 MyItemView 的呈现,这对于单元测试来说并不理想。这个问题的最佳解决方案是什么?我是 javascript 的新手,对此的解决方案似乎很复杂。
最佳答案
看看this SO关于如何使用 requireJS stub 依赖项。有一些解决方案。像 testrJs、squireJs 或我自己的小解决方案。主要思想是用你的 spy/stub/mock 覆盖 requireJs 依赖,这样你就可以只测试模块。
因此,在您的情况下,您可以像这样对 MyItemView stub :
var el = $("<div>test</div>")
var MyItemView = sinon.stub().returns({render: sinon.stub().returns(el)})
然后你必须将 MyItemView stub 注入(inject)到你的 require 上下文中,你可以测试测试 div 是否附加到
$('#myElement')
.这并不理想,因为所有 DOM 的东西,但它会工作。更好的方法是不要在主干 View 之外渲染一些东西。因为那么你可以注入(inject)一个模拟的 el
进入 View 并测试是否调用了模拟的附加方法。
关于unit-testing - 使用RequireJS(和Jasmine/Sinon)时如何 stub 在另一个 View 渲染方法中实例化的主干 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15837017/