2013-06-26 25 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(); 
    }); 
}); 
相关问题