具有默认范围

时间:2016-02-29 11:50:22

标签: javascript angularjs unit-testing angularjs-directive

我正在尝试对具有默认范围(范围:false)的指令进行单元测试,但我无法注入其控制器的依赖关系。

var MyApp = angular.module('MyApp',['MyDirectives','MyServices','MyControllers']);

这是指令

var MyDirectives = angular.module('MyDirectives', []);
MyDirectives.directive('myAddress', [ '$timeout', function ( $timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ctrl) {
            if (!ctrl) {
                return;
            }

            elm.on('focus', function () {
                scope.AppData.ShowSeparateAddress = false;
            });

        }
    };
}]);

这是我的控制器

var  MyControllers = angular.module(' MyControllers', []);
MyControllers.controller('Step1', [
'$rootScope', '$scope', 'AppData', function ($rootScope, $scope, AppData) {
  $scope.AppData = AppData.get();
   }

这是我的App Service

var  MyServices = angular.module(' MyServices', []);
    MyServices.factory('AppData', [function () {
    var data;
    return {
        get: function () {
            data = data || {};
            return data;
        }
    };
   }]);

这是地址指令的单元测试

beforeEach(module(MyApp));


var element, compiledElement, directiveElement;
var scope, compile, ele,AppData,controller;

beforeEach(inject(function(_$rootScope_, _$compile_){
scope = _$rootScope_.$new();
compile = _$compile_;
}));
 beforeEach(inject(function( _$controller_, _AppData_){

    AppData = _AppData_;
    controller = _$controller_('Step1',{scope:scope, AppData:AppData});
 }));
 function getCompiledElement(ele) {
     element = angular.element(ele);
     compiledElement = compile(element)(scope);
     scope.$digest();
     return compiledElement;
  }
it('should set show separate addrress as false when focussed',function(){
    ele = '<input type="text" data-my-address />';
    directiveElement = getCompiledElement(ele);
    console.log( directiveElement);
  expect( scope.AppData.ShowSeparateAddress ).toBe(false);
});

}); 我得到以下错误

Error: [$injector:unpr] Unknown provider: AppDataProvider <- AppData

我还试图通过提供来嘲笑服务,但它没有用 任何帮助或想法??

1 个答案:

答案 0 :(得分:0)

您的控制器签名中有三个参数,而您只传递两个参数。您应该添加$rootScope

controller = _$controller_('Step1',{rootScope:scope, scope:scope, AppData:AppData});