如何在Angular 1.3.14中测试需要另一个控制器的Angular指令?

时间:2015-03-16 14:53:47

标签: javascript angularjs jasmine

我试图为需要父指令存在的指令编写Jasmine测试。我发现了这个问题: Testing directives that require controllers但是,这有点过时了(Angular 1.1.5我相信),并且plunkr似乎不适用于新版本的Jasmine(2.2.1)和Angular(1.3.14) 。我明白了:

TypeError: undefined is not a function
    at Object.<anonymous>         (http://run.plnkr.co/AHQtPtvSezB4DsnJ/appSpec.js:18:33)

这里是代码: var app = angular.module(&#39; plunker&#39;,[]);

app.directive('foo', function() {
  return {
    restrict: 'E',
    controller: function($scope) {
      this.add = function(x, y) {
        return x + y;
      }
    }
  };
});

app.directive('bar', function() {
  return {
    restrict: 'E',
    require: '^foo',
    link: function(scope, element, attrs, foo) {
      scope.callFoo = function(x, y) {
        scope.sum = foo.add(x, y);
      }
    }
  };
});

测试:

describe('Testing directives', function() {
  var $scope, $compile, element;

  beforeEach(function() {
    module('plunker');

    inject(function($rootScope, _$compile_) {
      $scope = $rootScope.$new();
      $compile = _$compile_;
    });
  });

  it('ensures callFoo does whatever it is supposed to', function() {
    // Arrange
    var element = $compile('<foo><bar></bar></foo>')($scope);
    var fooController = element.controller('foo');
    var barScope = element.find('bar').scope();
    spyOn(fooController, 'add').andReturn(3);

    // Act
    barScope.callFoo(1, 2);

    // Assert
    expect(barScope.sum).toBe(3);
    expect(fooController.add).toHaveBeenCalledWith(1, 2);
  });
});

这是工作的掠夺者:

http://plnkr.co/edit/bC5BY81x0hi576xwSdyo?p=preview

我知道这个设计可能不是最好的,但是,我现在有点困惑。谢谢!

1 个答案:

答案 0 :(得分:0)

这个答案在上面提到的问题,方法#3工作得很好。我显然读得不够。

https://stackoverflow.com/a/19951141/629545