如何在 AngularJS 中测试广播事件 [英] How can I test Broadcast event in AngularJS

查看:29
本文介绍了如何在 AngularJS 中测试广播事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它在 rootscope 上发出广播事件.我想测试一下广播事件是否正确触发.

I have a controller which emits a broadcast event on the rootscope. I would like to test that the broacast event is fired correctly.

我的控制器中的代码如下所示:

My code in my controller looks like this:

   $scope.$watch("pageIndex", function(){
    if($scope.pageIndex == 4)
    {
      // emit social share
      $rootScope.$broadcast('myEvent');
    }
  });

我尝试使用以下代码对其进行测试:

I have tried to test it with the following code:

    it('Should call myEvent when pageIndex is 4',function(){
    scope.pageIndex = 4;
    scope.$apply();
    expect(rootScope.$on).toHaveBeenCalledWith('myEvent');
});

但它告诉我没有调用代码,我已经手动测试过它确实调用了.然后我尝试使用以下代码:

But it tells me that the code isn't called, which I have manually tested that it does. I have then tried with the following code:

it('Should call myEvent when pageIndex is 4',function(){
    var listener = jasmine.createSpy('listener');
    rootScope.$on('myEvent', listener);
    scope.pageIndex = 4;
    scope.$apply();
    expect(listener).toHaveBeenCalled();
});

但同样的负面结果.有没有办法测试一个事件是否被广播?

But with the same negative result. Is there a way to test that an event is broadcasted?

推荐答案

假设您使用的是 Jasmine,以下对我来说非常有用.

Assuming you're using Jasmine, the following is working great for me.

... other unit test setup code ...

var rootScope;
beforeEach(inject(function($injector) {
    rootScope = $injector.get('$rootScope');
    spyOn(rootScope, '$broadcast');
}));

describe("my tests", function() {
    it("should broadcast something", function() {
        expect(rootScope.$broadcast).toHaveBeenCalledWith('myEvent');
    });
});

如果您要广播消息并向其附加对象,您甚至可以测试这些对象是否符合预期

If you're broadcasting a message and attaching objects to it, you can even test that the objects match expectations

someObj = { ... something ... };
expect(rootScope.$broadcast).toHaveBeenCalledWith('someEvent', someObj);

这篇关于如何在 AngularJS 中测试广播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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