我喜欢有时包括我的控制器与指令,所以我需要一种方法来测试。
首先指令
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