我正在尝试对具有双向绑定属性 (=) 的指令进行单元测试。该指令在我的应用程序中有效,但我无法进行测试双向绑定的单元测试。
我一直试图让这个工作好几天。我已经阅读了许多示例,这些示例使用了我想使用的一些但不是全部功能:controllerAs、bindToController 和isolateScope()。(忘记我也需要的templateURL。如果我能做到这一点,我会补充一点!:)
我希望有人能告诉我如何显示隔离范围中反映的父范围的变化。
这是一个包含以下代码的 plunkr:
http://plnkr.co/edit/JQl9fB5kTt1CPtZymwhI
这是我的测试应用程序:
var app = angular.module('myApp', []);
angular.module('myApp').controller('greetingController', greetingController);
greetingController.$inject = ['$scope'];
function greetingController($scope) {
// this controller intentionally left blank (for testing purposes)
}
angular.module('myApp').directive('greetingDirective',
function () {
return {
scope: {testprop: '='},
restrict: 'E',
template: '<div>Greetings!</div>',
controller: 'greetingController',
controllerAs: 'greetingController',
bindToController: true
};
}
);
这是规格:
describe('greetingController', function () {
var ctrl, scope, rootScope, controller, data, template,
compile, isolatedScope, element;
beforeEach(module('myApp'));
beforeEach(inject(function ($injector) {
rootScope = $injector.get('$rootScope');
scope = rootScope.$new();
controller = $injector.get('$controller');
compile = $injector.get('$compile');
data = {
testprop: 1
};
ctrl = controller('greetingController', {$scope: scope}, data);
element = angular.element('<greeting-directive testprop="testprop"></greeting-directive>');
template = compile(element)(scope);
scope.$digest();
isolatedScope = element.isolateScope();
}));
// PASSES
it('testprop inital value should be 1', function () {
expect(ctrl.testprop).toBe(1);
});
// FAILS: why doesn't changing this isolateScope value
// also change the controller value for this two-way bound property?
it('testprop changed value should be 2', function () {
isolatedScope.testprop = 2;
expect(ctrl.testprop).toBe(2);
});
});