Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 测试指令中的简单函数,角度_Angularjs_Unit Testing_Karma Jasmine - Fatal编程技术网

Angularjs 测试指令中的简单函数,角度

Angularjs 测试指令中的简单函数,角度,angularjs,unit-testing,karma-jasmine,Angularjs,Unit Testing,Karma Jasmine,这是我的指示: angular.module('clientApp') .directive('positionDropDowns', function (CommonFactory) { return { templateUrl: 'template/position-drop-downs/position-drop-downs.html', restrict: 'E', scope: { districtsWithSubObje

这是我的指示:

angular.module('clientApp')
  .directive('positionDropDowns', function (CommonFactory) {
    return {
      templateUrl: 'template/position-drop-downs/position-drop-downs.html',
      restrict: 'E',
      scope: {
        districtsWithSubObjects: '='
      },
      link: function postLink(scope, element, attrs) {

        scope.hello = function(name){
          return 'hello ' + name;
        }
      }
    };
  });
如何测试
hello
功能?我试过这个:

describe('Directive: positionsDropDowns', function () {

  // load the directive's module
  beforeEach(module('clientApp'));

  beforeEach(module('template/position-drop-downs/position-drop-downs.html'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();

    element = angular.element('<position-drop-downs></position-drop-downs>');

    $rootScope.$digest();
  }));

  it('fn hello', inject(function ($compile) {
    expect(element.scope.hello('john')).toBe("hello john");

  }));
});
description('Directive:positionsDropDowns',function(){
//加载指令的模块
在每个模块之前(模块('clientApp');
每个模块之前(模块('template/position drop-downs/position drop-downs.html');
var元素,
范围
beforeach(注入(函数($rootScope){
scope=$rootScope.$new();
元素=角度。元素(“”);
$rootScope.$digest();
}));
它('fn hello',inject(函数($compile)){
expect(element.scope.hello('john')).toBe(“hello john”);
}));
});

I get
TypeError:undefined不是函数

您需要首先编译自定义指令:

beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
    element = $compile('<position-drop-downs></position-drop-downs>')(scope);
}));
URD.zeroflagL在注释中提供了访问独立指令范围的更优雅的方式。你也可以

expect(element.isolateScope().hello('john')).toBe("hello john");

注意,您需要访问独立的指令作用域。您可以使用
$$childTail
引用来完成此操作。

尝试
元素.scope()。您好('john')
这是jquery/jqlite插件。您可以使用$$childTail引用或
元素.isolateScope()
@zeroflagL来完成此操作。谢谢,这很有用。不知道有关
isolateScope
expect(element.isolateScope().hello('john')).toBe("hello john");