JavaScript – Backbone.js在浏览器中使用Sinon Spies查看测试

我正在为Backbone View编写一个测试,以测试在获取模型后调用render函数.测试是:
beforeEach(function () {
    $('body').append('<div class="sidebar"></div>');
    profileView = new ProfileView();
});

it('should call the render function after the model has been fetched',function (done) {
    profileView.model = new usermodel({md5: 'd7263f0d14d66c349016c5eabd4d2b8c'});
    var spy = sinon.spy(profileView,'render');
    profileView.model.fetch({
        success: function () {
            sinon.assert.called(spy);
            done();
        }
    });   
});

我使用Sinon Spies将一个间谍对象附加到profileView视图对象的render函数.

视图是:

var ProfileView = Backbone.View.extend({
    el: '.sidebar',template: Hogan.compile(ProfileTemplate),model: new usermodel(),initialize: function () {
        this.model.bind('change',this.render,this);
        this.model.fetch();
    },render: function () {
        $(this.el).html(this.template.render());
        console.log("Profile Rendered");
        return this;
    }
});

在测试中调用提取后,更改事件将触发,并且视图的渲染函数正在被调用,但是Sinon间谍没有检测到渲染被调用并失败.

作为一个实验,我尝试在测试中调用render函数来查看Spy是否识别出它:

it('should call the render function after the model has been fetched','render');
    profileView.render();
    profileView.model.fetch({
        success: function () {
            sinon.assert.called(spy);
            done();
        }
    });   
});

在间谍侦测到被叫是在上述情况.

有人知道为什么间谍没有在初始测试中识别渲染调用吗?

解决方法

问题是,在构造视图期间,初始化函数将事件直接绑定到render函数.您无法使用间谍拦截此事件,因为在设置间谍之前已经发生绑定(您在构建之后执行此操作).

在构建视图之前,该解决方案是在原型上进行间谍.所以你必须将间谍移动到beforeEach,或将视图的构造移动到测试中.

设置间谍:

this.renderSpy = sinon.spy(ProfileView.prototype,'render');
this.view = new ProfileView();

然后,删除间谍:

ProfileView.prototype.render.restore()

然后这将会窥探“普通”的调用,以及来自模型的更改事件.

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面