【问题标题】:testing $emit in angular directive's controller在角度指令的控制器中测试 $emit
【发布时间】:2016-06-16 01:42:57
【问题描述】:

我对在控制器内部测试 $emit 有点困惑。我正在设置的控制器存在于指令中。我对设置测试的两个部分感到困惑。如何在测试中设置 $emit?我正在使用 Jasmine,所以我做了一个

    spyON(scope, '$emit')

我的测试找不到要监视的对象。这是我的测试。

describe('hero Directive', function () {
    var $compile,
        $rootScope,
        scope,
        element,
        ctrl;

    beforeEach(function () {
        angular.mock.module('ha.module.core');

我正在定义控制器并在注入内设置范围。我编译了 html,以便可以使用该指令。

        angular.mock.inject(function (_$compile_, _$rootScope_, _$controller_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            scope = $rootScope.$new();

我认为错误可能出在控制器中,但似乎设置正确。

            ctrl = _$controller_('ExploreHeroController', { scope: scope });

该指令使用 templateUrl 我希望我可以通过模拟 div 进行测试并编译它。

            var html = '<div explore-hero></div>';
            element = $compile(angular.element(html))(scope);
            scope.$digest();
        });

    });

    describe('directive controller', function () {
        it('should dispatch call $emit with $methodsBound', function () {
            spyOn(scope, '$emit');

            //expect(scope.$emit).toHaveBeenCalledWith('$methodsBound');
        });
    });

});

发射位于我的指令控制器内

var controller = function($scope) {
    $scope.$emit('$methodsBound');
}

【问题讨论】:

    标签: unit-testing angular-directive


    【解决方案1】:

    你的指令创建了一个孤立的范围,它调用 $emit,所以你需要定义这个:

     var elementScope;
     //beforeEach 
     el = angular.element('<your-directive></your-directive>');
     $compile(el)(scope);
     scope.$digest(); 
     elementScope = el.isolateScope();
    
     it('should spy isolated scope', function(){
          spyOn(elementScope, '$emit');
          expect(elementScope.$emit).toHaveBeenCalledWith('$methodsBound');
     })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多