我喜歡有時包括我的控制器與指令,所以我需要一種方法來測試。
首先指令
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'EA',
scope: {},
controller: function ($scope) {
$scope.isInitialized = true
},
template: '<div>{{isInitialized}}</div>'
}
})
則測試:
describe("myDirective", function() {
var el, scope, controller;
beforeEach inject(function($compile, $rootScope) {
# Instantiate directive.
# gotacha: Controller and link functions will execute.
el = angular.element("<my-directive></my-directive>")
$compile(el)($rootScope.$new())
$rootScope.$digest()
# Grab controller instance
controller = el.controller("myDirective")
# Grab scope. Depends on type of scope.
# See angular.element documentation.
scope = el.isolateScope() || el.scope()
})
it("should do something to the scope", function() {
expect(scope.isInitialized).toBeDefined()
})
})
更多的方式來從一個實例化的指令得到的數據見angular.element documentation。
請注意,實例化指令意味着控制器和所有鏈接函數已經運行,因此可能會影響您的測試。
請問有什麼要點測試指令的控制器與指令本身分開?我懷疑如果控制器的代碼沒有沿着指令的其餘部分進行測試,那麼你做錯了什麼。這有點像說我有這個類的方法,但我想單獨測試它,所以我將把它放在全局範圍內。我認爲接受的答案(pkozlowski)涉及不好的練習,而詹姆斯的答案是正確的。 – Izhaki 2015-08-20 14:58:22