如何测试 angular 指令的 templateUrl 指向的 HTML? [英] How do I test the HTML pointed to by the templateUrl of an angular directive?

查看:24
本文介绍了如何测试 angular 指令的 templateUrl 指向的 HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令:

app/controllers/battle.js

angular.module('myModule').controller('myController',['$范围',功能($范围){$scope.sayHello = function(){console.log('hello');};}]).directive('myDirective', function(){返回 {templateUrl: '../views/testView.html'}});

该指令的调用方式如下:

app/views/routeOne.html

指令 templateUrl 指向一个看起来像这样的文件:

app/views/testView.html

你好

<div id='eggs'>这是一些鸡蛋.</div>

如何使用 karma/jasmine 进行单元测试以确保 testView.html 中的 div id 存在?

尝试的方法:

  1. 根据 this stackoverflow answer 使用 ngHtml2Js.失败原因:不清楚如何访问创建的模块,新创建的模块如何帮助访问/查询 testView.html 文件中的 DOM 元素,不清楚在 testView.html 必须指向的 4 个地方中的每个地方使用什么路径.

  2. 使用 Html2Js 根据 这篇博文. 失败原因:类似于 (1).

  3. 使用 jquery.ajax 访问模板,按照 这篇文章.原因失败:angular router 阻止我简单地直接查询文件,尽管我可以通过 curl 或我的浏览器直接访问它.在许多尝试的路线上失败.可能不仅仅是角度路由器阻止了这种方法的工作.

  4. 根据角度文档<使用$compile/a>.原因失败:未找到 $compile,或未找到指令,或编译指令未返回任何内容.

在互联网上搜索如何测试作为 angular 指令模板的 HTML 文件会产生许多不同的方法,但我没有设法使它们起作用.我很高兴使用上述任何一种方法,但我还没有找到一个可以从头到尾以整体方式带我并涵盖足够多的实际情况来回答我的问题的指南.那么:如何测试指令使用的 HTML?

我建议解决方案 1 进行一些更改.

指令的小改动.

angular.module('myModule').controller('myController',['$scope',function($scope){$scope.sayHello = function(){console.log('hello');};}])指令('我的指令',函数(){返回 {templateUrl: '../views/testView.html',控制器:'我的控制器'}});

在 karma.conf.js 中

插件:[//还有一些其他插件'karma-ng-html2js-预处理器'],预处理器:{"path/to/templates/**/*.html": ["ng-html2js"]},ngHtml2Js预处理器:{//如果您的构建过程更改了模板的路径,//使用 stripPrefix 和 prependPrefix 对其进行调整.stripPrefix: "应用程序",prependPrefix: "..",//要创建的 Angular 模块的名称模块名称:模板"},

现在在 battel.spec.js//测试文件

describe('指令测试', function () {beforeEach(module('templates'));beforeEach(module('myModule'));var $compile, $rootScope;beforeEach(inject(function (_$compile_, _$rootScope_) {//注入器在匹配时从参数名称周围解开下划线(_)$compile = _$compile_;$rootScope = _$rootScope_;}));it('一些测试', function(){var element = $compile("<my-directive></my-directive>")($rootScope);$rootScope.$apply();expect(element.html()).toContain('这里有一些鸡蛋');});});

I have a directive:

app/controllers/battle.js

angular.module('myModule')
  .controller('myController',
  ['$scope',
  function($scope){
    $scope.sayHello = function(){console.log('hello');};
  }])
  .directive('myDirective', function(){
    return {
      templateUrl: '../views/testView.html'
    }
  });

That directive is called as follows:

app/views/routeOne.html

<my-directive ng-controller='myController'></my-directive>

The directive templateUrl points to a file that looks like:

app/views/testView.html

<div id='testView'>Hello</div>
<div id='eggs'>Here are some eggs.</div>

How do I unit test with karma/jasmine to ensure that the div id in testView.html exists?

Methods tried:

  1. Using ngHtml2Js as per this stackoverflow answer. Reason failed: Unclear on how to access the created module, how the newly created module helps access/query the DOM elements in the testView.html file, unclear what path to use in each of the 4 places testView.html must be pointed to.

  2. Using Html2Js as per this blogpost. Reason failed: Similar to (1).

  3. Accessing the template with jquery.ajax as per this article. Reason failed: angular router prevented me from simply querying straight to the file, though I could access it directly via curl or my browser. Failed on many attempted routes. Probably not only angular router preventing this method from working.

  4. Using $compile as per the angular docs. Reason failed: $compile not found, or, directive not found, or, compiling the directive not returning anything.

Trawling across the internet for how to test an HTML file that's the template for an angular directive yields many different methods, none of which I've managed to make work. I'm happy to use any of the above methods, but I've yet to find a guide that can take me from start to finish in a holistic manner and cover enough of what's happening to actually answer my question. So: how can I test the HTML used by my directive?

解决方案

I would suggest solution 1 with some changes.

A small change in directive.

angular.module('myModule')
   .controller('myController',['$scope',function($scope){
         $scope.sayHello = function(){console.log('hello');};
    }])
   directive('myDirective', function(){
      return {
        templateUrl: '../views/testView.html',
        controller: 'myController'
      }
   });

In karma.conf.js

plugins: [
        // some other plugins as well
        'karma-ng-html2js-preprocessor'
    ],
preprocessors: {
     "path/to/templates/**/*.html": ["ng-html2js"]
},

ngHtml2JsPreprocessor: {
    // If your build process changes the path to your templates,
    // use stripPrefix and prependPrefix to adjust it.
    stripPrefix: "app",
    prependPrefix: "..",
    // the name of the Angular module to create
    moduleName: "templates"
},

Now in battel.spec.js //test file

describe('Directive Tests', function () {
    beforeEach(module('templates'));
    beforeEach(module('myModule'));

    var $compile, $rootScope;

    beforeEach(inject(function (_$compile_, _$rootScope_) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
   }));
  it('Some test', function(){
       var element = $compile("<my-directive></my-directive>")($rootScope);
       $rootScope.$apply();
       expect(element.html()).toContain('Here are some eggs');
  });
});

这篇关于如何测试 angular 指令的 templateUrl 指向的 HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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