如何在 AngularJS 中测试 $broadcast 和 $on 事件
How to test $broadcast and $on events in AngularJS
我正在尝试测试 Angular 中的 $broadcast 和 $on 事件。
我有一个创建日期并对其进行一些计算的函数,然后通过 $broadcast 将结果发送到另一个控制器。
我想做的是测试 $broadcast 是否发生以及 $on 侦听器以查看结果。
我可以测试前者,但后者失败了。
我已经创建了一个 JSFiddle,其中包含我想要在此处实现的目标的基本示例 http://jsfiddle.net/devonCream/zhbjfunm/6/
有效
expect(rootScope.$broadcast).toHaveBeenCalledWith('sendTime',tDate);
});
但是....
expect(rootScope.$on).toHaveBeenCalledWith('sendTime', Function);
给予
Expected spy $on to have been called with [ 'sendTime', Function ] but actual calls were [ 'sendTime', Function ]
和我一模一样!
(为了加分,谁能告诉我为什么我的 fiddle 不能在 https 上运行!)。
而不是:
expect(rootScope.$on).toHaveBeenCalledWith('sendTime', Function);
尝试:
expect(rootScope.$on).toHaveBeenCalledWith('sendTime', jasmine.any(Function));
[更新]
工作fiddle
http://jsfiddle.net/zhbjfunm/10/
time = time
是主要的麻烦!
谢谢鲍里斯的回答,虽然你的解决方案确实使测试成功,但我没有完成我需要的东西,但给我指明了正确的方向,我需要做的是重新发送事件并在第二个控制器中获取结果,所以。
it('Should have time set on 2nd controllers scope', function () {
mainScope.sendEvent();
expect(subScope.currentTime).toBe('2015-03-20T10:00:05');
});
工作!
谢谢。
我正在尝试测试 Angular 中的 $broadcast 和 $on 事件。 我有一个创建日期并对其进行一些计算的函数,然后通过 $broadcast 将结果发送到另一个控制器。
我想做的是测试 $broadcast 是否发生以及 $on 侦听器以查看结果。
我可以测试前者,但后者失败了。
我已经创建了一个 JSFiddle,其中包含我想要在此处实现的目标的基本示例 http://jsfiddle.net/devonCream/zhbjfunm/6/
有效
expect(rootScope.$broadcast).toHaveBeenCalledWith('sendTime',tDate);
});
但是....
expect(rootScope.$on).toHaveBeenCalledWith('sendTime', Function);
给予
Expected spy $on to have been called with [ 'sendTime', Function ] but actual calls were [ 'sendTime', Function ]
和我一模一样!
(为了加分,谁能告诉我为什么我的 fiddle 不能在 https 上运行!)。
而不是:
expect(rootScope.$on).toHaveBeenCalledWith('sendTime', Function);
尝试:
expect(rootScope.$on).toHaveBeenCalledWith('sendTime', jasmine.any(Function));
[更新]
工作fiddle
http://jsfiddle.net/zhbjfunm/10/
time = time
是主要的麻烦!
谢谢鲍里斯的回答,虽然你的解决方案确实使测试成功,但我没有完成我需要的东西,但给我指明了正确的方向,我需要做的是重新发送事件并在第二个控制器中获取结果,所以。
it('Should have time set on 2nd controllers scope', function () {
mainScope.sendEvent();
expect(subScope.currentTime).toBe('2015-03-20T10:00:05');
});
工作!
谢谢。