问题描述
在尝试测试视图是否正确绑定到事件时,我遇到了一些有趣的困难.在主干中,我们通常在初始化方法中绑定到事件,使用类似于以下内容的内容:something.bind("change", this.render);
.在我的测试中,我想确保设置了这个绑定,所以我做了以下事情:
I had some interesting tribulations in trying to test whether views were correctly bound to events. In backbone, we typically bind to events in the initialize method, using something along the lines of: something.bind("change", this.render);
. In my test, I want to make sure that this binding is set up, so I did the following:
this.myView = new MyView();
spyOn(this.myView, "render");;
this.legendView.groupData.trigger("change");
expect(this.legendView.render).toHaveBeenCalled();
但是,这行不通.因为绑定发生在 MyView 的初始化函数中,所以事件在那个时间绑定到了 myView 的渲染函数.因此,当您添加间谍时,它会包装渲染函数并将其设置回 myView.render 中的位置.但是第一次绑定创建的闭包仍然存在,我们完全被骗了.那么我们能做些什么呢?我所做的是将绑定调用移至单独的函数,例如:
But, that won't work. Because the bind occurs in MyView's initialize function, the event get's bound to myView's render function AT THAT TIME. So, when you add your spy, it wraps the render function and sets it back into place at myView.render. But the closure created by the first bind still exists, and we are totally hozed. So what can we do about it? What I did, is move my bind call's to a seperate function, something like:
myView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, "render");
this.initialize_model_bindings();
},
initialize_model_bindings: function(){
something.bind("change", this.render);
},
render: function(){ //... }
});
然后我的测试看起来像:
and my test then looks like:
this.myView = new MyView();
spyOn(this.myView, "render");
this.myView.initialize_model_bindings();
this.legendView.groupData.trigger("change");
expect(this.legendView.render).toHaveBeenCalled();
这可行,但我正在寻找更好的解决方案.谢谢
This works, but I'm looking for a better solution. Thanks
推荐答案
与其监视回调,不如尝试监视 something.bind.然后测试是否使用适当的参数调用了绑定.到目前为止,这对我有用.我正在使用 sinon.js 而不是 jasmine 的内置间谍.sinon.js 使测试传递给相同方法调用堆栈中的方法调用的参数变得更容易一些(例如,在视图初始化中绑定的一堆调用).所以我没有单独用茉莉花测试过这个想法,但相信它应该是可能的.
Instead of spying on the callback you might try spying on something.bind. Then test that bind was called w/ the appropriate arguments. This is working for me so far. I'm using sinon.js instead of jasmine's built-in spies. sinon.js makes it a bit easier to test for args passed to a method call in a stack of same method calls (eg a bunch of calls to bind in a view init). So I haven't tested this idea w/ jasmine alone but believe it should be possible.
spyOn(this.legendView.groupData, 'bind');
this.myView = new MyView();
expect(this.legendView.groupData.mostRecentCall.args).toEqual('change', this.myView.render); // example!! only works if testing a single call to bind or the last call in a series (ie mostRecentCall)
还有带有 sinon.js 的
And w/ sinon.js
sinon.spy(this.legendView.groupData, 'bind');
this.myView = new MyView();
expect(this.legendView.groupData.bind.calledWith('change', this.myView.render); // works w/ any number of calls to bind
这篇关于用茉莉花测试backbone.js应用程序-如何测试视图上的模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!