2013-06-26 5 views
1

페이지의 컨트롤러와 별도의 컨트롤러를 사용하는 AngularJS 지시문에 대한 단위 테스트를 작성하려고합니다. 그러나 테스트에서 해당 컨트롤러에 액세스 할 수있는 방법을 찾을 수 없습니다.자체 컨트롤러가있는 각도 명령 테스트

'use strict'; 
angular.module('myapp.directives') 
    .directive('searchButton', function() { 
    function SearchButtonCtrl ($scope, $location) { 
     $scope.search = function() { 
     $location.path('/search'); 
     $location.search(q, $scope.query.w); 
     }; 
    } 
    return { 
     template: '<input type="text" ng-model="query.q">', 
     controller: SearchButtonCtrl, 
     restrict: 'E' 
    }; 
    }); 

SearchButtonCtrl 액세스 할 수 있습니다 :

여기 내 지시인가? 또는 액세스 할 수 있도록 내 코드를 구조화하는 더 좋은 방법이 있습니까?

답변

2

이 경우 컨트롤러에 액세스하는 방법은 컨트롤러가 테스트 입력을 구성 할 HTML 스 니펫에서 해당 범위에 배치하는 기능을 사용하는 것입니다.

참고 : 재 스민 스파이의 사용은 과도 할 수 있으며, 인수를 $ location.path() 및/또는 $ location.search()에 일치시키는 올바른 방법을 찾지 않았습니다.), 그러나 이것은 당신이 찾고있는 관찰을위한 장소로 갈고리를 찾는 것을 돕기에 충분해야합니다.

'use strict'; 

describe('Directive: Search', function() { 

    var element, $location; 

    // Load your directive module with $location replaced by a test mock. 
    beforeEach(function() { 
     module('myapp.directives'), function() { 
      $provide.decorator('$location', function($delegate) { 
       $delegate.path = jasmine.createSpy(); 
       $delegate.search = jasmine.createSpy(); 

       return $delegate; 
      }); 
     }); 

     inject(function(_$location_) { 
      $location = _$location_; 
     }); 
    }); 

    it('changes the path', function() { 
     // Arrange to trigger your directive code 
     element = $element.html('<span ng-init="query.q = 'xyz'"><search><span ng-init="search()"></span></search></span>'); 

     // Express your directive's intended behavior 
     expect($location.path).toHaveBeenCalled(); 
    }); 

    it('changes a search param', function() { 
     // Arrange to trigger your directive code 
     element = $element.html('<span ng-init="query.q = 'xyz'"><search><span ng-init="search()"></span></search></span>'); 

     // Express your directive's intended behavior 
     expect($location.search).toHaveBeenCalled(); 
    }); 
});