javascript - 在单元测试中获取 Controller 的编译模板

标签 javascript angularjs unit-testing controller jasmine

我有以下 Controller :

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>

现在我想在我的测试中创建一个 Controller ,看看它何时渲染是否正确渲染:

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

虽然不确定如何获取元素。

[更新]

我实际上是在尝试测试一个模板,因为这是由 Controller 使用的,我想用 Controller 测试它,但正如 Jon 所建议的那样,它可以作为模板加载。

我不知道如何让它编译和操作作用域并再次编译。以下内容:

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.Page to edit users. 的输出,看起来元素只是未编译的原始元素一个。

尝试这样的事情也没什么用:

  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 运行时可用。然后这样做:

变量范围=空;

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/

关于javascript - 在单元测试中获取 Controller 的编译模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837571/

相关文章:

javascript - 拒绝加载字体 '<URL>' 因为它违反了以下内容安全策略指令 default-src ,所以 default-src 被用作后备

javascript - Discord机器人: Fix ‘FFMPEG not found’

javascript - 如何使用 Angular 注册现有元素?

使用 TestCoroutineDispatcher(已弃用)替代方案对 Kotlin 协程进行 Android 测试

java - 跨浏览器测试、布局测试和持续集成

javascript - 我在从表单值填充新的 Javascript 数组时遇到困难

javascript - jQuery(或 javascript)验证日期范围

javascript - 为什么 Angular 的标题过滤器对我不起作用?

java - 无法从Spring Controller 中的http post正文读取参数

C++测试框架: recommendation sought