我正在测试AngularJS指令的控制器。
describe('The directive', function() {
var element,
scope;
beforeEach(module('app'));
beforeEach(module('path/to/theDirective'));
beforeEach(inject(function($compile, $rootScope) {
element = angular.element('<div args="args" the-directive ></div>');
scope = $rootScope;
$compile(element)(scope);
scope.args = {
availableValues : [1, 2, 3],
key : 'id',
selectedValues : [],
searchText : '',
flag: false
};
scope.$digest();
}));
it('should compile', function() {
expect(element.html()).not.toBeNull();
});
describe('directive controller', function() {
var controller;
beforeEach(inject(function($controller) {
controller = element.controller('theDirective', {
$scope: scope
});
}));
it('should exist', function() {
expect(controller).not.toBeNull();
expect(controller).toBeDefined();
expect(scope.disableAddButton()).toBeDefined();
});
});
});
第一个it
块传递,因此指令正在成功编译。第二个describe
块未通过。第二个describe
it
块中的前两个断言通过,但第三个断言没有通过。它正在返回TypeError: 'undefined' is not a function (evaluating 'scope.disableAddButton()')
。是否可能未正确注入控制器,或者是否需要进行更多设置?
答案 0 :(得分:1)
事实证明,范围需要隔离,因为指令的控制器是私有功能。
在mAdapter.notifyDataSetChanged();
之后添加scope = element.isolateScope() || element.scope();
可以解决问题。此外,将控制器声明移动到第一个scope.$digest();
块并不是一个坏主意。
固定测试看起来像这样:
beforeEach