2015-09-16 124 views
2

有以下控制器定義:如何在Jasmine測試中注入控制器依賴關係?

angular.module('app.controllers', []).controller('HomeController', [ 
    '$scope', '$modal', 'Point', function($scope, $modal, Point) { //some action } 

我要測試的這款控制器:

describe('HomeController', function() { 
    beforeEach(module('app.controllers')); 

    var $controller; 

    beforeEach(inject(function(_$controller_){ 
    // The injector unwraps the underscores (_) from around the parameter names when matching 
    $controller = _$controller_; 
    })); 

    describe('$scope.grade', function() { 
    it('sets the strength to "strong" if the password length is >8 chars', function() { 
     var $scope = {}; 
     var controller = $controller('HomeController', { $scope: $scope }); 
     $scope.label = '12345'; 
     $scope.addNewPoint(); 
     expect($scope.label).toEqual(null); 
    }); 
    }); 
}); 

「點」是我的定製服務,「$模式」是角引導模塊。我如何在我的測試中注入它?提前致謝!

回答

4

服務應該自動注入。如果你想嘲笑他們或者監視他們,他們注入像這樣:

describe('HomeController', function() { 
    beforeEach(module('app')); 

    var $controller, $scope, $modal, Point; 

    beforeEach(inject(function(_$controller_, _$rootScope_, _$modal_, _Point_){ 
    $scope = $rootScope.$new(); 
    $modal = _$modal_; 
    Point = _Point_; 

    spyOn($modal, 'method'); 
    spyOn(Point, 'method'); 

    $controller = _$controller_('HomeController', { $scope: $scope, $modal: $modal, Point: Point }); 
    })); 

    describe('$scope.grade', function() { 
    it('sets the strength to "strong" if the password length is >8 chars', function() { 
     $scope.label = '12345'; 
     $scope.addNewPoint(); 
     expect($scope.label).toEqual(null); 
    }); 
    }); 
}); 
+0

如果我不注入的服務,我得到錯誤「未知提供商:$ modalProvider < - $模式」 – malcoauri

+0

爲$模態,從UI來.bootstrap?如果是這樣,在初始化模塊之前添加'beforeEach(module('ui.bootstrap'))''。 – Lee

+1

這是正確的!我剛剛改變了'app.controllers'的'應用程序',它的工作原理!我在一行中注入了所有依賴關係:)謝謝!編輯你的答案,我會標記它 – malcoauri