我有以下控制器:
angular.module('app').controller('userList'
, ['$scope','appRules',function ($scope,appRules) {
$scope.isUserInRole=function(user,role){
console.log("exucuting userIsInRole:",user,role);//never happens
return appRules.userIsInRole(user,role);
}
window.sscope=$scope;
console.log($scope.menu);
}]);
这用于以下路线:
angular.module('app', [,'ui.bootstrap','ngRoute'])
.config(['$routeProvider','$locationProvider'
,function($routeProvider,$locationProvider){
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
$routeProvider
.when('/admin/users',{
templateUrl:'app/js/partials/admin/users/list.html',
controller:'userList'
});
}]);
该模板将包含一些内容来检查用户是否可以看到此页面(即使有人破解了 javascript,也没关系,因为当获取或提交数据时,服务器也会进行检查)。
<div data-ng-if="!isUserInRole(login.user,'Administrator')" class="red">
Please log in or log in as another user.
</div>
<div data-ng-if="isUserInRole(login.user,'Administrator')" class="green">
Page to edit users.
</div>
现在我想在测试中创建一个控制器,并查看它何时渲染是否正确渲染:
var controller,scope,element;
beforeEach(inject(function($controller
,$rootScope,$compile,appRules) {
scope=$rootScope;
scope.login={};
scope.isUserInRole=appRules.userIsInRole;
controller = $controller('userList',{
$scope:scope
});
//here I have the controller but how to get the html it generates
// when rendering the template?
element = $compile("<div ng-controller='userList'>"
+"<div data-ng-view=''></div></div>")(scope);
//here element isn't rendered at all, works on directives but how
// to do this with controllers?
console.log("element is:",element);
}));
我想写一个像这样的测试
it('Check page won\'t show if user is not set or is not Administrator.'
, function() {
expect($(element).text().trim()
.indexOf("Please log in or log in as another user."))
.toBe(0,'Show login message when login.user is not set.');
});
但不确定如何获取元素。
[update]
我实际上正在尝试测试一个模板,因为这是由控制器使用的,我正在考虑使用控制器来测试它,但正如乔恩建议的那样,它可以作为模板加载。
我不知道如何使其编译和操作范围并再次编译。下列:
var el = angular.element(
$templateCache
.get('app/js/partials/admin/users/list.html'));
$rootScope = _$rootScope_;
$rootScope.menu={login:{}};
el.scope($rootScope);
$rootScope.$apply();
console.log(el.text());
这给了我两者的输出Please log in or log in as another user.
and Page to edit users.
看起来 element 只是未编译的原始元素。
尝试这样的事情也没有多大作用:
beforeEach(inject(function(_$compile_
, _$rootScope_,appSettings,$templateCache){
console.log("before each");
var el = angular.element($templateCache
.get('app/js/partials/admin/users/list.html'));
var compile=_$compile_;
var $rootScope=_$rootScope_;
$rootScope.login:{};
$rootScope.isUserInRole=appSettings.userIsInRole;
//I would think that compile would invoke the ng-if and appSettings.userIsInRole
// but no console log in that function is shown.
var element = compile($templateCache
.get('app/js/partials/admin/users/list.html'))($rootScope);
console.log("element is:",element.html());//=undefined
}));