6

Karma 単体テストにディレクティブのテンプレート (すべてが異なるスクリプト タグの 1 つのファイルにある) を含める方法を理解するのに苦労しています。

私が得るエラー:

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

1 に答える 1

7

あなたのエラーは、HTML ファイルを通常は JavaScript を受け入れるファイル リストにロードしようとしていることが原因だと思います。私はあなたのための解決策を持っています。

始める前に、カルマ 0.10.2 を使用していますが、0.8.x 以下を使用しているように見えますか? これは 0.10.2 で動作していますが、0.8.x をインストールできません。0.8.x に翻訳してみますが、自分が行っていることをテストすることができないため、主に 0.10.x に関して説明します。可能であれば、とにかく最新のカルマに移動する方が簡単かもしれません.

設定

0.10.x

外部 HTML パーシャルはkarma-ng-html2js-preprocessorによってロードできます。templateUrlこれは通常、 および同様のメソッドを介してディレクティブに直接ロードするために使用されます。0.10.2 では、このパッケージが (npm を使用して) インストールされていることを確認してから、カルマ構成に以下を含める必要があります。

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。これは angularscriptディレクティブを使用して行われるため、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 パーシャルをテストにプッシュするための機能が既にありますが、メイン テンプレートを適切に解釈できる機能が欠けていました。

于 2013-10-21T00:20:12.883 に答える