【发布时间】:2014-10-01 02:17:38
【问题描述】:
在这个小提琴http://jsfiddle.net/FlavorScape/fp1kktt9/ 中,我尝试在控制器上设置属性,而不是直接设置 $scope。在模板(生产中)中,我们只做 myAliasCtrl.somePropertyList 并且 ng-repeat 工作。
但是,这在测试中不起作用。我不知道如何获取/分配控制器上的属性。
更新: 我的测试环境中一定有一些奇怪的本地化问题,因为我确实让 ng-repeat 工作。请注意如何有两个子元素,即使该属性位于别名控制器上。 http://jsfiddle.net/FlavorScape/2adn983y/2/
但是,我的问题仍然是,我如何获得对该编译控制器的引用来创建间谍?(或者只是获得对别名控制器的引用)?
来源:
angular.module('myApp', [])
.directive('myTestDirective', function () {
return {
restrict: 'E',
scope: {
myBinding: '='
},
replace: true,
template: '<div ng-if="isRendered">TEST<div ng-repeat="foo in myCtrl.fooList">{{foo}}</div></div>',
controller: 'myTestController',
controllerAs: 'myCtrl'
};
})
.controller('myTestController', function($scope) {
$scope.isRendered = true;
// if i reference this, ng-repeat works
$scope.fooList = ["boob","cat", "Tesla"];
});
describe('myTest directive:', function () {
var scope, compile, validHTML;
validHTML = '<div><my-test-directive my-binding="isRendered"></my-test-directive></div>'; //i
beforeEach(module('myApp'));
beforeEach(inject(function($compile, $rootScope){
scope = $rootScope.$new();
scope.isRendered = true;
compile = $compile;
}));
function create() {
var elem, compiledElem;
elem = angular.element(validHTML);
compiledElem = compile(elem)(scope);
scope.$digest();
return compiledElem;
}
it('should have a scope on root element', function () {
var el = create();
// how to get the controller???
el.scope().myCtrl.fooList = ["monkey","apple","Dishwasher"];
// notice it just has <!-- ng-repeat
console.log( el );
expect(el.text()).toContain('TEST');
});
});
【问题讨论】:
-
另外,我什至如何访问 myCtrl 实例,比如说,添加一个间谍?
-
实际上,您会注意到它“编译”了,但控制器从不设置 isRendered 属性。
标签: angularjs unit-testing controller directive