2013-06-26 24 views
1

我正在嘗試爲AngularJS指令編寫單元測試,該指令使用頁面上的單獨控制器。但是,我無法從我的測試中找到任何訪問該控制器的方法。用他們自己的控制器測試Angular指令

這裏是我的指令:

'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(); 
    }); 
}); 
相關問題