实例化控制器

时间:2016-03-03 22:18:05

标签: angularjs unit-testing angularjs-directive jasmine

我正在努力启动控制器位于指令内。我需要运行一些测试但是现在我无法使用ng-Mock访问控制器。

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

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

    angular.mock.inject(function (_$compile_, _$rootScope_, _$controller_, $templateCache) {


        $compile = _$compile_;
        element = angular.element("<div exlore-hereo></div");
        $compile(element)($rootScope);
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        ctrl = _$controller_('ExploreHeroController', { $scope: $scope });
        console.log(ctrl)


        $scope.$digest();
    });

});

afterEach(function () {
    // need to remove the element element.remove();
});

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


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

});

我创建了一个编译它的元素并调用$ digest方法。

我得到的错误是

  Argument 'scope' is required.   

所以我试着用茉莉花来监视它

spyON($ scope,&#39; ControllerName&#39;);

我的指令中的控制器非常基本。

var ControllerName = function($scope) {
   $scope.$emit('$method');
}

好像我需要一个间谍,但我不确定为什么我创建的那个不起作用。

1 个答案:

答案 0 :(得分:1)

您可以尝试侦听$ scope,但请注意ControllerName不是$scope对象的成员。

然而,$emit是....

问题是,你在控制器构造中调用$emit,因此你必须在之前监视它:

beforeEach(function () {
    ...    
        $scope = $rootScope.$new();
        spyOn($scope, '$emit');
        ctrl = _$controller_('ExploreHeroController', { $scope: $scope });
    ...
});

describe('directive controller', function () {
    it('should dispatch call $emit with $methodsBound', function () {
    expect($scope.$emit).toHaveBeenCalledWith('$methodsBound');
});

});