如何注入在AngularJS一个指令单元测试服务(How to inject a service i

2019-08-18 20:24发布

我需要测试指令,做一些注射服务几个电话。 下面的代码段是一个例子指令,监听活动,并重定向如果输入被按下指定的元素内的浏览器。

编辑: 我得到我可以在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.

Answer 1:

To decorate, stub, provide mocks or override any given service, you may use the $provide service. $provide.value, $provide.decorator etc. Documentation here.

Then you can do stuff like this:

 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');

}));


文章来源: How to inject a service in a directive unit test in AngularJS