我怎样才能测试$ rootScope。$ emit事件? [英] How can I test $rootScope.$emit event?

查看:88
本文介绍了我怎样才能测试$ rootScope。$ emit事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 abc 控制器中有以下代码:

I have below code in abc controller:

   $rootScope.$on('selectedItem', function (event, data) {
       vm.selectedItem = data;
   });

调用函数位于 xyz 控制器:

  function doThis(){
     $rootScope.$emit('selectedItem', 'somedata');
  }

如何在业力测试中复制或模拟这种情况?

How can I reproduce or mock this scenario in karma test?

推荐答案

对于第一个控制器( abc ),您可以使用<$ c听取它$ c> $ rootScope。$ on ,你可以先 $ rootScope。$ emit 它和 $ scope。$ digest ()它。这样你就可以在 $ 上收到它。

For first controller (abc), where you listen to it using $rootScope.$on, you can first $rootScope.$emit it and $scope.$digest() it. So that you can receive it in $on.

var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
}));

describe("some function", function() {
    it("should receive selectedItem with $on", function() {
        rootScope.$emit('selectedItem', 'somedata');
        $scope.$digest();
        expect(vm.selectedItem).toEqual('somedata');
    });
});

对于第二个控制器( xyz ),您可以在 $ rootScope。$ emit spy 。并且期望 xyz 控制器中调用它。像这样:

And for second controller (xyz), You can spy on $rootScope.$emit. And expect it to be called in xyz controller. Like this:

var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
    spyOn(rootScope, '$emit');
}));

describe("doThis function", function() {
    it("should $emit selectedItem", function() {
        vm.doThis(); // or if you use $scope, call it that way
        expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
    });
});

这篇关于我怎样才能测试$ rootScope。$ emit事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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