单元测试指令的模板都是一个带有脚本标记的文件都是、指令、脚本、标记

2023-09-13 03:07:38 作者:乖一点就爱你

我有一个很难搞清楚如何将我的噶单元测试我的指令的模板(即都在以不同的脚本标记一个文件)。

错误我得到:

PhantomJS 1.9(Linux)的错误 语法错误:解析错误 在/var/www/html/tweak/core/global/views/js/modules/datable/templates.html:1PhantomJS 1.9(Linux)的:执行的0 ERROR(0.313秒/ 0秒)0

下面是code的相关部分:

我的指令肉:

  {回报  范围       : {    列:'=',    配置:'='  },  templateUrl:确定时代/ table.html',  限制:'E',  控制器:'datableCtrl',  链接:linkingFunction}; 

我的模板文件:

 <脚本类型=文/ NG-模板ID =确定时代/ table.html>  <! - 数据行 - >  &所述; TR    NG-重复=行中的行跟踪由$ ID($指数)    类=确定时代行    NG-隐藏=加载>    < TD      NG-重复=列列跟踪由$ ID($指数)      NG-CLASS ={编辑 - 在':'在'编辑模式==}      类={{column.classes.join('')+'列'+ $指数}}      NG-风格=column.style>      < D​​IV NG-包括=编辑模式=='上'和;&安培; column.editable        ? 确定时代/ editCell.html        :确定时代/ normalCell.html'>      < / DIV>    < / TD>    <! - 保存按钮 - >    < TD NG秀=编辑模式=='对'的风格=WIDTH:1px的;>      <按钮类=BTN>保存< /按钮>    < / TD>    <! -  /保存按钮 - >  < / TR>  <! -  /数据行 - >< / SCRIPT><脚本类型=文/ NG-模板ID =确定时代/ editCell.html>  < D​​IV NG-开关=column.inputType>    <! - 文本输入 - >    < D​​IV NG-开关时=文本>      < D​​IV纳克级={        投入追加':column.append ='',        输入 -  prePEND':!柱prePEND =''      }>        <跨度          类=附加          列prePENDNG秀= GT; {{列prePEND}}< / SPAN>        <输入          TYPE =文本          NG-模型=行[column.model]          NG-KEYDOWN =查询()          NG-CLASS =inputClass.join('')          NG-ATTRS =column.inputAttrs>        <跨度          类=附加          NG-秀=column.append> {{column.append}}< / SPAN>      < / DIV>    < / DIV>    <! - 结束文本输入 - >    <! - 选择输入 - >    < D​​IV NG-开关时=选择>      <选择        NG-模型=行[column.model]        NG-变化=查询()        NG-选项=item.value作为item.name为项column.options        NG-CLASS =inputClass.join('')        NG-ATTRS =column.inputAttrs>        <期权价值=> - < /选项>      < /选择>    < / DIV>    <! - 最终选择 - >    <! - 收音机/复选框 - >    < D​​IV NG开关默认>      <标签NG重复=(键,值)column.options轨道由$ ID($指数)>        <输入          TYPE ={{column.inputType}}          NG-CLASS =inputClass.join('')          NG-变化=查询()          值={{键}}          NG-检查=行[column.model] .indexOf(钥匙)-1个          NG-ATTRS =column.inputAttrs>        <跨度> {{}值}< / SPAN>      < /标签>    < / DIV>    <! - 结束收音机/复选框 - >  < / DIV>< / SCRIPT><脚本类型=文/ NG-模板ID =确定时代/ normalCell.html>  < D​​IV CLASS =只读>    <跨度> {{列prePEND}}< / SPAN>    <! - <跨度> {{行[column.model] | datableFilter:column.filter}}< / SPAN> - >    <跨度NG绑定HTML的不安全=(行[column.model] +')| datableFilter:column.filter>< / SPAN>    <跨度> {{column.append}}< / SPAN>  < / DIV>< / SCRIPT> 
基于自定义向导的C 单元测试环境自动化配置

我的单元测试:

 使用严格描述(确定时代,函数(){  描述('指令',函数(){    变量$ rootScope,$编译元素;    beforeEach(模块('确定时代'));    beforeEach(模块('的/ var / www / html等/ TWEAK /核心/全球/视图/ JS /模块/确定时代/ templates.html'));    beforeEach(注(功能(_ $ rootScope_,_ $ compile_){      $ rootScope = _ $ rootScope_;      $编译= _ $ compile_;      $ rootScope.tableConfig = {        编辑:真      };      $ rootScope.columns = [];      元素= angular.element('<确定时代的配置=tableConfig列=列>< /确定时代>');        $编译(元)($ rootScope);        $ rootScope $摘要()。    }));    它('应该有NG-scope类',函数(){        期待(element.hasClass('NG-范围'))TOBE(真)。    });  });}); 

我噶配置:

  VAR支='好办法';基本路径='在/ var / www / html等/+支部+'/';文件= [  //依赖  茉莉,  JASMINE_ADAPTER,  https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js',  https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js',  的http://$c$c.angularjs.org/1.1.5/angular-mocks.js',  //其他要求  核心/全球/视图/ JS /模块/ REST / module.js',  //项目源  核心/全球/视图/ JS /模块/确定时代/ module.js',  核心/全球/视图/ JS /模块/确定时代/ values​​.js',  核心/全球/视图/ JS /模块/确定时代/ services.js',  核心/全球/视图/ JS /模块/确定时代/ filters.js',  核心/全球/视图/ JS /模块/确定时代/ directives.js',  核心/全球/视图/ JS /模块/确定时代/ controllers.js',  核心/全球/视图/ JS /模块/确定时代/ *。HTML,  //我的规格套装  核心/全球/视图/ JS /模块/确定时代/ tests.js];排除= [];记者= ['进步'];端口= 9876;runnerPort = 9100;颜色= TRUE;LOGLEVEL = LOG_INFO;autoWatch =真;浏览器= ['PhantomJS'];captureTimeout = 60000; 

解决方案

我觉得你的错误是因为你想你的HTML文件加载到该正常接受的JavaScript文件列表。我有你的解决方案,但。

在我开始之前,我有因缘0.10.2,它看起来像你是在0.8.4或下?我在0.10.2这个工作,但我不能安装0.8.x.我会尽力为翻译而0.8.4将不能够测试我在做什么,所以我将主要描述0.10.x.方面它可能会更容易,如果你能移动到最新的人缘呢。

配置

0.10.x

外部HTML谐音可以通过karma-ng-html2js-$p$pprocessor.这通常用于通过 templateUrl 和类似的方法指令直接加载。在0.10.2你需要确保这个软件包安装(使用NPM),然后在您的业力的配置如下:

  preprocessors:{    ** / * HTML':'NG-html2js']},ngHtml2Js preprocessor:{    cacheIdFromPath:功能(文件路径){        //如果你有一个以上的HTML文件,你会想在这里做一些更聪明。        返回'inlinetemplates';    },    MODULENAME:inlinetemplates},插件:    ...    卡玛 -  NG-html2js- preprocessor]文件:    ...    应用程序/ alltemplates.html',//主模板HTML    //不包括那些在文件上面的内联单独的文件路径] 

这将允许您加载使用模块模块('inlinetemplates')将插入你的主模板文件的内容(而不是单个模板)为 $ templateCache

0.8.4

因此​​,翻译为0.8.4 ......我认为你需要使用 html2js 这是不那么强大,但包含在这个版本的业力。您不需要在插件安装或包括它,你不能配置如何使用它,所以你只需要

  preprocessors = {'** / * HTML。':'html2js']} 

模块创建的,该项目其插入 $ templateCache 将使用您用它来参考您的主模板的html路径来命名。

的JavaScript

0.10.x

现在,你应该能够加载相关模块,并得到使用你的主模板文件中的内容访问

  VAR模板= $ templateCache.get('inlinetemplates') 

所有剩下要做的就是推动从主模板文件内容的内联模板 $ templateCache 。这是使用角剧本指令完成的,所以我们只需要编译/链接我们已经加载了棱角分明的文件。为此,您可以非常简单地用

  $编译(模板)(范围); 

所以把这个在一起,您可以在需要加载你的模板任何描述块以下。

  beforeEach(模块('inlinetemplates'));beforeEach(注(函数($编译,$ templateCache,$ rootScope){    变种templatesHTML = $ templateCache.get('inlinetemplates');    $编译(templatesHTML)($ rootScope);})); 

0.8.4

  VAR mainTemplateLocation ='路径/使用/到/参考/到/主/模板/中/人缘/ conf.html';beforeEach(模块(mainTemplateLocation));beforeEach(注(函数($编译,$ templateCache,$ rootScope){    VAR templatesHTML = $ templateCache.get(mainTemplateLocation);    $编译(templatesHTML)($ rootScope);})); 

小结

同样,我不能保证0.8.4指令会的工作,特别是没有调整,但是这肯定0.10.x工作。

噶已经为推动外部HTML谐音为你的测试,所有缺少的是能够跨preT你的主模板正常。

设施

I am having a hard time figuring out how to include my directive's templates (that are all in one file in different script tags) in my Karma unit tests.

The error I get:

PhantomJS 1.9 (Linux) ERROR
 SyntaxError: Parse error
 at /var/www/html/tweak/core/global/views/js/modules/datable/templates.html:1
PhantomJS 1.9 (Linux): Executed 0 of 0 ERROR (0.313 secs / 0 secs)

Here are the relevant parts of the code:

My directives meat:

return {
  scope       : {
    columns : '=',
    config  : '='
  },
  templateUrl : 'datable/table.html',
  restrict    : 'E',
  controller  : 'datableCtrl',
  link        : linkingFunction
};

My template file:

<script type="text/ng-template" id="datable/table.html">
  <!-- data rows -->
  <tr
    ng-repeat="row in rows track by $id($index)"
    class="datable-row"
    ng-hide="loading">

    <td
      ng-repeat="column in columns track by $id($index)"
      ng-class="{'edit-on': editMode == 'on'}"
      class="{{column.classes.join(' ') + ' column' + $index}}"
      ng-style="column.style">

      <div ng-include="editMode == 'on' && column.editable
        ? 'datable/editCell.html'
        : 'datable/normalCell.html'">
      </div>
    </td>

    <!-- save button -->
    <td ng-show="editMode == 'on'" style="width:1px;">
      <button class="btn"> Save </button>
    </td>
    <!-- / save button -->

  </tr>
  <!-- / data rows -->
</script>

<script type="text/ng-template" id="datable/editCell.html">
  <div ng-switch="column.inputType">

    <!-- text input -->
    <div ng-switch-when="text">
      <div ng-class="{
        'input-append'  : column.append != '',
        'input-prepend' : column.prepend != ''
      }">

        <span
          class="add-on"
          ng-show="column.prepend"> {{column.prepend}} </span>

        <input
          type="text"
          ng-model="row[column.model]"
          ng-keydown="query()"
          ng-class="inputClass.join(' ')"
          ng-attrs="column.inputAttrs">

        <span
          class="add-on"
          ng-show="column.append"> {{column.append}} </span>
      </div>
    </div>
    <!-- end text input -->

    <!-- select input -->
    <div ng-switch-when="select">
      <select
        ng-model="row[column.model]"
        ng-change="query()"
        ng-options="item.value as item.name for item in column.options"
        ng-class="inputClass.join(' ')"
        ng-attrs="column.inputAttrs">

        <option value=""> -- </option>
      </select>
    </div>
    <!-- end select -->

    <!-- radio / checkbox -->
    <div ng-switch-default>
      <label ng-repeat="(key, value) in column.options track by $id($index)">
        <input
          type="{{column.inputType}}"
          ng-class="inputClass.join(' ')"
          ng-change="query()"
          value="{{key}}"
          ng-checked="row[column.model].indexOf('key') > -1"
          ng-attrs="column.inputAttrs">

        <span> {{value}} </span>
      </label>
    </div>
    <!-- end radio / checkbox -->

  </div>
</script>

<script type="text/ng-template" id="datable/normalCell.html">
  <div class="read-only">
    <span> {{column.prepend}} </span>
    <!-- <span> {{row[column.model] | datableFilter : column.filter}} </span> -->
    <span ng-bind-html-unsafe="(row[column.model] + '') | datableFilter : column.filter"></span>
    <span> {{column.append}} </span>
  </div>
</script>

My unit tests:

'use strict'

describe("datable", function() {

  describe('directive', function () {
    var $rootScope, $compile, element;

    beforeEach(module('datable'));
    beforeEach(module('/var/www/html/tweak/core/global/views/js/modules/datable/templates.html'));

    beforeEach(inject(function (_$rootScope_, _$compile_) {
      $rootScope = _$rootScope_;
      $compile = _$compile_;

      $rootScope.tableConfig = {
        editable     : true
      };
      $rootScope.columns = [];

      element = angular.element('<datable config="tableConfig" columns="columns"></datable>');

        $compile(element)($rootScope);
        $rootScope.$digest();
    }));

    it('should have ng-scope class', function() {
        expect(element.hasClass('ng-scope')).toBe(true);
    });
  });
});

My Karma config:

var branch = 'tweak';
basePath = '/var/www/html/' + branch + '/';

files = [
  // Dependencies
  JASMINE,
  JASMINE_ADAPTER,
  'https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js',
  'https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js',
  'http://code.angularjs.org/1.1.5/angular-mocks.js',

  // other requirements
  'core/global/views/js/modules/rest/module.js',

  // the project source
  'core/global/views/js/modules/datable/module.js',
  'core/global/views/js/modules/datable/values.js',
  'core/global/views/js/modules/datable/services.js',
  'core/global/views/js/modules/datable/filters.js',
  'core/global/views/js/modules/datable/directives.js',
  'core/global/views/js/modules/datable/controllers.js',
  'core/global/views/js/modules/datable/*.html',

  // my spec suite
  'core/global/views/js/modules/datable/tests.js'
];

exclude = [

];

reporters = ['progress'];
port = 9876;
runnerPort = 9100;
colors = true;
logLevel = LOG_INFO;
autoWatch = true;
browsers = ['PhantomJS'];
captureTimeout = 60000;

解决方案

I think your error is because you are trying to load your HTML file into a file list that normally accepts javascript. I do have a solution for you though.

Before I begin, I have karma 0.10.2 and it looks like you are on 0.8.x or under? I have this working in 0.10.2 but I can't install 0.8.x. I'll try to translate for 0.8.x but won't be able to test what I'm doing, so I'll describe mainly in terms of 0.10.x. It may be easier to move to latest karma anyway if you are able.

Config

0.10.x

External HTML partials can be loaded by karma-ng-html2js-preprocessor. This is normally used for loading directly in directives via templateUrl and similar methods. In 0.10.2 you need to make sure this package is installed (using npm) and then include the following in your karma config:

preprocessors: {
    '**/*.html' : ['ng-html2js']
},

ngHtml2JsPreprocessor: {
    cacheIdFromPath: function(filepath) {
        // If you had more than one html file you would want to do something more clever here.
        return 'inlinetemplates';
    },
    moduleName: 'inlinetemplates'
},

plugins: [
    ...,
    'karma-ng-html2js-preprocessor'
],

files: [
    ...,
    'app/alltemplates.html', // your main template html
    // Don't include paths for individual files that are inlined in the file above
]

This will allow you to load a module with module('inlinetemplates') that will insert the contents of your main template file (not the individual templates) into $templateCache.

0.8.x

So, translating for 0.8.x... I think you need to use html2js which is not so powerful but is included in karma in this version. You won't need to install or include it in plugins, and you can't configure how it's used, so you just need

preprocessors = { '**/*.html': ['html2js'] }

The module created, and the item it inserts into $templateCache will be named using the path that you use to refer to your main template html.

Javascript

0.10.x

Now you should be able to load the relevant module and get access to the contents of your main template file using

var templates = $templateCache.get('inlinetemplates')

All that is left to do is pushing your inlined templates from the main template file contents to $templateCache. This is done using the angular script directive, so we just need to compile/link the file we have loaded with angular. You can do this very simply with

$compile(templates)(scope);

So putting this together, you can include the following in any describe block that needs to load your templates.

beforeEach(module('inlinetemplates'));
beforeEach(inject(function($compile, $templateCache, $rootScope) {
    var templatesHTML = $templateCache.get('inlinetemplates');
    $compile(templatesHTML)($rootScope);
}));

0.8.x

var mainTemplateLocation = 'path/used/to/refer/to/main/templates/in/karma/conf.html';
beforeEach(module(mainTemplateLocation));
beforeEach(inject(function($compile, $templateCache, $rootScope) {
    var templatesHTML = $templateCache.get(mainTemplateLocation);
    $compile(templatesHTML)($rootScope);
}));

Summing Up

Again, I can't guarantee that the 0.8.x instructions will work, especially not without tweaking, but this certainly works in 0.10.x.

Karma already has the facilities for pushing external HTML partials into your tests, all that was missing was being able to interpret your main template properly.