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

unit testing of directive with default scope

本文关键字:指令 单元测试 范围 默认      更新时间:2023-09-26

我正在尝试对具有默认作用域(scope: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();
   }

这是我的应用服务

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

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

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

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