unit-testing - 使用RequireJS(和Jasmine/Sinon)时如何 stub 在另一个 View 渲染方法中实例化的主干 View

标签 unit-testing backbone.js requirejs jasmine sinon

我正在尝试使用 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/

相关文章:

java - jaxb xjc - 如何生成单元测试文件

javascript - 在 sails.js 中模拟/ stub 全局变量

javascript - Backbone : before route

javascript - 带有 jQ​​ueryMobile-Router 的 Require.js

javascript - 是否可以将 Javascript 函数参数的属性扩展到本地范围?

javascript - 使用 require.js 缓存时的调试

asp.net-mvc-4 - 如何为使用 StatusCode 404 抛出 HttpException 的 Action 编写单元测试

unit-testing - 如何在 Python 中模拟 sqlite3.connect

backbone.js - 将模型添加到集合时不触发添加事件

javascript - 主干 View 在没有指定预定义 el 的情况下不呈现