对一个指令进行单元测试,该指令的模板都是带有脚本标签的文件

2024-05-08

我很难弄清楚如何在我的 Karma 单元测试中包含我的指令模板(全部位于不同脚本标记的一个文件中)。

我得到的错误:

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)

以下是代码的相关部分:

我的指令肉:

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

我的模板文件:

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

我的单元测试:

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

我的业力配置:

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;

我认为你的错误是因为你试图将 HTML 文件加载到通常接受 javascript 的文件列表中。不过我确实有一个解决方案给你。

在开始之前,我有 karma 0.10.2,看起来您使用的是 0.8.x 或更低版本?我可以在 0.10.2 中使用此功能,但无法安装 0.8.x。我将尝试翻译 0.8.x,但无法测试我正在做的事情,因此我将主要用 0.10.x 进行描述。如果可以的话,无论如何,转移到最新的业力可能会更容易。

Config

0.10.x

外部 HTML 部分可以通过以下方式加载karma-ng-html2js-预处理器 https://github.com/karma-runner/karma-ng-html2js-preprocessor。这通常用于通过直接加载指令templateUrl和类似的方法。在 0.10.2 中,您需要确保安装此软件包(使用 npm),然后在 karma 配置中包含以下内容:

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
]

这将允许您加载模块module('inlinetemplates')这会将主模板文件(而不是单个模板)的内容插入到$templateCache.

0.8.x

所以,翻译为 0.8.x...我认为你需要使用html2js虽然不是那么强大,但在此版本中包含在业力中。您不需要安装它或将其包含在插件中,并且无法配置它的使用方式,因此您只需要

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

创建的模块及其插入的项目$templateCache将使用您用来引用主模板 html 的路径来命名。

JavaScript

0.10.x

现在您应该能够加载相关模块并使用以下命令访问主模板文件的内容

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

剩下要做的就是将内联模板从主模板文件内容推送到$templateCache。这是使用角度完成的script指令,所以我们只需要编译/链接我们用 Angular 加载的文件。你可以非常简单地做到这一点

$compile(templates)(scope);

因此,将这些放在一起,您可以在任何内容中包含以下内容describe需要加载模板的块。

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

加起来

再次强调,我不能保证 0.8.x 指令能够工作,尤其是在不进行调整的情况下,但这在 0.10.x 中肯定有效。

Karma 已经具备将外部 HTML 部分推送到测试中的功能,所缺少的只是能够正确解释您的主模板。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对一个指令进行单元测试,该指令的模板都是带有脚本标签的文件 的相关文章

随机推荐