间谍与茉莉花Backbone.js的查看功能 [英] Spy on Backbone.js View Functions with Jasmine

查看:162
本文介绍了间谍与茉莉花Backbone.js的查看功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个茉莉花规范验证,当一个模型被添加到视图的集合视图的函数被调用。

I'm trying to write a Jasmine spec to verify that a view's function is called when a model is added to the view's collection.

在视图的初始化函数我

this.collection.on('add', this.fooAdded, this);

在我的茉莉花规范我做:

In my Jasmine spec I'm doing:

describe('Foo View', function() {
   it('should call fooAdded when a Foo is added', function() {
      var view = new FooView({collection: new FooCollection()});
      spyOn(view, 'fooAdded').andCallThrough();
      view.delegateEvents();
      view.collection.add({name: 'foo'});
      expect(view.fooAdded).toHaveBeenCalled();
   });
});

我fooAdded()的执行记录的东西到控制台,所以我知道它被称为。然而,间谍没有看到fooAdded()被调用。

My implementation of fooAdded() logs something to the console, so I know it's being called. However the spy doesn't see that the fooAdded() has been called.

请参阅我的的jsfiddle

推荐答案

您的问题是, spyOn 替换暗中监视功能与新的包装函数,但是您要更换它的之后的功能已被使用。通过调用时间 spyOn(看来,fooAdded')附上您的间谍,给参照原 fooAdded 已经在收集的侦听器列表所以它是太晚了窥视的回调。

Your problem is that spyOn replaces the spied on function with a new wrapper function but you're replacing it after the function has been used. By the time you call spyOn(view, 'fooAdded') to attach your spy, a reference to the original fooAdded is already in the collection's listener list so it is too late to spy on that callback.

如果您在视图中的原型在 fooAdded 间谍的的实例化视图:

If you spy on the fooAdded in the view's prototype before instantiating your view:

spyOn(FooView.prototype, 'fooAdded');
var view = new FooView(...);
view.delegateEvents();
//...

接下来的事情应该更好地工作。演示: http://jsfiddle.net/m5Baw/1/ (感谢的amiuhle 更新在演示茉莉花链接)。

then things should work better. Demo: http://jsfiddle.net/m5Baw/1/ (thanks to amiuhle for updating the Jasmine links in the demo).

顺便说一句,我觉得奇怪的东西在你的看法是怎么回事,你应该不需要 view.delegateEvents()视图的code之外,所以你可能想在该仔细看看。

As an aside, I think something strange is going on your view, you shouldn't need to view.delegateEvents() outside the view's code so you might want to have a closer look at that.

这篇关于间谍与茉莉花Backbone.js的查看功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆