programing

Angular에서의 지시 장치 테스트에서 서비스를 주입하는 방법JS

iphone6s 2023. 2. 26. 09:19
반응형

Angular에서의 지시 장치 테스트에서 서비스를 주입하는 방법JS

주입된 서비스에 대한 호출을 수행하는 명령을 테스트해야 합니다.다음 코드 조각은 지정된 요소 내에서 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
    };
  }]);

문제는 내가 그들을 감시하기 위해 어떻게 서비스를 투입해야 하는지 알지 못한다는 것이다.

제안 솔루션은 다음과 같습니다.서비스를 제대로 삽입하지 못해 예상대로 작동하지 않습니다.

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

}));

언급URL : https://stackoverflow.com/questions/15753009/how-to-inject-a-service-in-a-directive-unit-test-in-angularjs

반응형