如何在AngularJS中测试$broadcast和$events



我正在尝试测试Angular中的$broadcast和$on事件。我有一个函数,它创建一个日期并对其进行一些计算,然后通过$broadcast将结果发送到另一个控制器。

我想做的是测试$broadcast和$on监听器,看看结果如何。

我可以测试前者,但后者失败了。

我创建了一个JSFiddle,其中有一个我试图在这里实现的基本示例http://jsfiddle.net/devonCream/zhbjfunm/6/

Works

   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 ]

看起来和我一模一样!

(为了获得加分,有人能告诉我为什么我的小提琴不能在https上工作吗!)。

代替:

expect(rootScope.$on).toHaveBeenCalledWith('sendTime', Function);

尝试:

expect(rootScope.$on).toHaveBeenCalledWith('sendTime', jasmine.any(Function));

[更新]

工作小提琴

http://jsfiddle.net/zhbjfunm/10/

time = time 

是主要的麻烦!

感谢Boris的回答,尽管您的解决方案确实使测试工作正常,但我没有完全给我所需要的,而是为我指明了正确的方向,我需要做的是重新发送事件并在第二个控制器中获取结果,所以。

    it('Should have time set on 2nd controllers scope', function () {
        mainScope.sendEvent(); 
        expect(subScope.currentTime).toBe('2015-03-20T10:00:05');
    });

工作!

谢谢。

最新更新