2014-01-17 75 views
3

我想完全理解如何用Jasmine測試AngularJS中的指令。目前,我有一個設置如下所示的指令:AngularJS中的單元測試指令控制器

.directive('myDirective', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     replace: true, 
     scope: { 
      title:'=', 
      state:'@' 
     }, 
     templateUrl: 'myHtml.tpl.html', 
     controller: function ($scope) { 
      // Business Logic Specific to the Directive goes in here 
     } 
    }; 
}) 

如上面的代碼片斷所示,我的指令在指令定義中有一個控制器。我試圖測試的具體指令相當複雜。指令中的控制器有超過200行代碼。我試圖弄清楚如何編寫圍繞這個控制器內容的單元測試。目前我有以下幾種:

describe('myApp', function() { 
    var $scope; 

    beforeEach(module('myApp')); 
    beforeEach(inject(function ($controller, $rootScope) { 
     $scope = $rootScope.$new(); 
    })); 

    it('should create my directive', inject(function ($rootScope, $compile, $log) { 
     var card = angular.element('<my-directive></my-directive>'); 
     $compile(card)($rootScope); 
     $scope.$digest(); 

     expect($log.assertEmpty).not.toThrow(); 
    })); 
}); 

上面的單元測試測試了指令本身的創建。但是,我無法弄清楚如何測試控制器內部的指令。有沒有辦法做到這一點?如果是這樣,怎麼樣?

謝謝!

回答

4

至於我記得有像一個指令分離器語法:

.directive('myDirective', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     replace: true, 
     scope: { 
      title:'=', 
      state:'@' 
     }, 
     templateUrl: 'myHtml.tpl.html', 
     controller: 'MyDirectiveCtrl as ctrl' 
    }; 
}) 

,並註冊爲一個普通控制器

.controller("MyDirectiveCtrl", function($scope) {}) 

所以,如果你這樣做,那麼你可以通過使用$控制器創建此控制器並愉快地進行測試。

1

您可以用下面的代碼測試控制器:

describe('myApp', function() { 
var $scope; 

beforeEach(module('myApp')); 
beforeEach(inject(function ($controller, $rootScope) { 
    $scope = $rootScope.$new(); 
    var card = angular.element('<my-directive></my-directive>'); 
    $compile(card)($rootScope); 
    $scope.$digest(); 
    controller = element.controller 
})); 

it('should create my directive', inject(function ($rootScope, $compile, $log) { 
    //TRY YOUR BUSINESS LOGIC TESTS HERE 
    //$scope.yourFunction(yourArgs...); 
    //expect($scope.yourVars).toSomething 
})); 

});

+0

如果控制器正在注入服務,有沒有辦法測試它?或者這隻適用於傳遞所有信息的「啞」指令? –

+0

它應該是控制器= card.controller? – Brant