简体   繁体   English

具有默认范围的指令的单元测试

[英]unit testing of directive with default scope

I am trying to unit test a directive which has default scope(scope:false) but I am not able to inject dependency of its controller. 我正在尝试对具有默认作用域(scope:false)的指令进行单元测试,但无法注入其控制器的依赖项。

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

Here is the directive 这是指令

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;
            });

        }
    };
}]);

Here is my controller 这是我的控制器

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

Here is my App Service 这是我的应用服务

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

Here is the unit test for address directive 这是地址指令的单元测试

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);
});

}); }); I get this following error 我收到以下错误

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

I have also trieed mocking the service through provide but it did not work Any help or idea ?? 我也尝试通过提供来嘲笑该服务,但是它没有用。任何帮助或想法?

You have three arguments in your controller signature and you are passing only two. 控制器签名中有三个参数,并且只传递了两个参数。 You should add the $rootScope : 您应该添加$rootScope

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM