Fla*_*ape 5 unit-testing controller directive angularjs
在这个小提琴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');
});
});
Run Code Online (Sandbox Code Playgroud)
一切都按预期工作:)你只是试图访问错误的范围.
因为ngIf创建了一个新范围,所以应该访问该范围(因为isRendered在该子范围上创建:
expect(el.children().first().scope().isRendered).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)
这是更新的小提琴.
更新:
您正在使用controllerAs,基本上您将控制器this绑定到范围属性.例如controllerAs: 'myTestCtrl'隐式结果$scope.myTestCtrl = this;(this控制器实例在哪里).
但是你再次尝试访问错误的元素.你需要包装的第一个子元素,<div>然后你需要它的隔离范围(不是正常的范围):
var ctrl = el.children().first().isolateScope().myTestCtrl;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2882 次 |
| 最近记录: |