在单元测试中获取控制器的编译模板 [英] Get compiled template for controller in unit test

查看:95
本文介绍了在单元测试中获取控制器的编译模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下控制器:

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无关紧要,因为当提取或提交数据时服务器也会检查)。

The template would have something that will check if user can see this page or not (even if someone hacks javascript it doesn't matter because when data is fetched or submitted the server checks as well).

<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>

现在我想在我的测试中创建一个控制器,看看它呈现的时间是否正确呈现:

Now I would like to create a controller in my test and see when it renders if it renders correctly:

  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.');
  });

不知道如何获得元素。

[更新]

我实际上是在尝试测试一个模板,因为我正在考虑用它来测试它一个控制器,但是Jon建议它可以作为模板加载。

I'm actually trying to test a template, because this is used by a controller I was thinking testing it with a controller but as Jon suggested it can just be loaded as template.

如何使它编译和操作范围并再次编译我不知道。以下内容:

How to make it compile and manipulate scope and compile again I don't know. The following:

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());

这给我输出请登录或以其他方式登录用户。用于编辑用户的页面。看起来元素只是未编译的原始元素。

This gives me the output of both Please log in or log in as another user. and Page to edit users. Looks like element is just the raw element not compiled one.

尝试这样的事情也没有太大作用:

Trying something like this doesn't do much either:

  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    
  }));


推荐答案

使用ng-templates将模板添加到缓存中ng-html2js所以当Karma运行时它们可用。然后执行以下操作:

Add your templates to the cache using ng-templates or ng-html2js so they are available when Karma runs. Then do this:

var scope = null;

var scope = null;

beforeEach(inject(function($templateCache,_$compile_,_$rootScope_, _$controller_) {

    //get the template from the cache
    template = $templateCache.get('src/main/app/components/someController/widget-search.tpl.html');

    $compile = _$compile_;
    $rootScope = _$rootScope_;
    $controller = _$controller_;

    scope = $rootScope.new();
    //compile it
    element = $compile(template)(scope);
}));

 //then shove your compiled element into your controller instance



it( 'should be instantiated since it does not do much yet', function(){

            ctrl = $controller('SomeController',
                {
                    $scope: scope,
                    $element: element
                });

             scope.$digest();

            // my controller should set a variable called hasInstance to true when it initializes. Here i'm testing that it does.
            expect( ctrl.hasInstance).toBeTruthy();

        });

有关详细信息,请参阅 http://angular-tips.com/blog/2014/06/introduction-to-unit-test-directives/

For more info, see http://angular-tips.com/blog/2014/06/introduction-to-unit-test-directives/

这篇关于在单元测试中获取控制器的编译模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆