在指令中测试一个简单的函数,angular

时间:2015-03-23 14:35:07

标签: 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: {
        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");

  }));
});

我得到TypeError: undefined is not a function

1 个答案:

答案 0 :(得分:0)

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

beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
    element = $compile('<position-drop-downs></position-drop-downs>')(scope);
}));

之后,应使用hello方法填充范围对象:

it('fn hello', inject(function ($compile) {
    expect(scope.$$childTail.hello('john')).toBe("hello john");
}));
注释中的

URD。 zeroflagL为访问隔离指令范围提供了更优雅的方式。你也可以

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

注意,您需要访问隔离的指令范围。您可以使用$$childTail引用来执行此操作。