【问题标题】:jasimine argument scope is required when instantiating a controller实例化控制器时需要 jasimine 参数范围
【发布时间】:2016-03-03 22:18:04
【问题描述】:

我正在努力启动一个位于指令内的控制器。我有一些需要运行的测试,但现在我无法使用 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, 'ControllerName');

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

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

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

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive jasmine


    【解决方案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');
    });
    

    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多