如何在AngularJS的指令单元测试中注入服务



我需要测试一个指令,它调用了一些注入的服务。下面的代码是一个示例指令,它监听事件,并在指定元素中按enter键时重定向浏览器。

编辑:我得到的感觉我可能是在E2E测试土地涉水?

angular.module('fooApp')
  .directive('gotoOnEnter', ['$location', function ($location) {
    var _linkFn = function link(scope, element, attrs) {
        element.off('keypress').on('keypress', function(e) {
                  if(e.keyCode === 13)
                  {
                       $location.path(scope.redirectUrl);
                  }
              });
    }
    return {
      restrict: 'A',
      link: _linkFn
    };
  }]);

问题是我还没有弄清楚如何在指令中注入服务来监视它们。

我的解决方案是这样的:它没有工作,正如预期的那样,因为我没有成功地注入$locacion服务来监视。

describe('Directive: gotoOnEnter', function () {
  beforeEach(module('fooApp'));
  var element;
  it('should visit the link in scope.url when enter is pressed', inject(function ($rootScope, $compile, $location) {
    element = angular.element('<input type="text" goto-on-enter>');
    element = $compile(element)($rootScope);
    $rootScope.redirectUrl = 'http://www.google.com';
    $rootScope.$digest();
    var e = jQuery.Event('keypress');
    e.keyCode = 13;
    element.trigger(e);
    spyOn($location, 'path');
    expect($location.path).toHaveBeenCalledWith('http://www.google.com');
  }));

这个收益率

Expected spy path to have been called with [ 'http://www.google.com' ] but it was never called.

要装饰、存根、提供模拟或覆盖任何给定的服务,您可以使用$provide服务。$provide.value, $provide.decorator等。文档在这里。

然后你可以这样做:

 var $location;
 beforeEach(function() {
    module('studentportalenApp', function($provide) {
      $provide.decorator('$location', function($delegate) {
        $delegate.path = jasmine.createSpy();
        return $delegate;
      });
    });
    inject(function(_$location_) {
      $location = _$location_;
    });
  });

it('should visit the link in scope.redirectUrl when enter is pressed', inject(function ($rootScope, $compile, $location) {
    element = angular.element('<input type="text" goto-on-enter>');
    element = $compile(element)($rootScope);
    $rootScope.redirectUrl = 'http://www.google.com';
    $rootScope.$digest();
    var e = jQuery.Event('keypress');
    e.keyCode = 13;
    element.trigger(e);
    $rootScope.$digest();
    expect($location.path).toHaveBeenCalledWith('http://www.google.com');
}));

最新更新