AngularJS + Jasmine:间谍事件回调

arn*_*ton 2 javascript jasmine angularjs

我有问题spyOn方法绑定到具有范围.$ on的事件在工厂服务中,使用Jasmine.最初传递的真实方法被称为,而不是间谍.我做了一个plinkr:http://plnkr.co/edit/2RPwrw?p = preview

谢谢你的帮助.

Mic*_*ley 7

这是因为你绑定回调的方式.更改

service.$on('hello', service.method);
Run Code Online (Sandbox Code Playgroud)

service.$on('hello', function() {
  service.method();
});
Run Code Online (Sandbox Code Playgroud)

当你说spyOn(service, 'method'),你说"用service.method间谍替换引用的值".但是,当事件被触发时,您的原始service.$on代码不会在service.method上查找值 - 而是在初始化服务时查找它.因此,更改指向以后的引用无效.service.method