ngMock に関連していることは間違いありません。ngMock モジュールは、すべての Angular テストに対して自動的にロードされ、モックを初期化して、テンプレートのフェッチを含むサービス$httpBackendの使用を処理します。$httpテンプレート システムがテンプレートを読み込もうとする$httpと、モックに対する「予期しない要求」になります。
テンプレートを にプリロードして$templateCache、Angular がテンプレートを要求したときにテンプレートを使用せずに使用できるようにする方法が必要です$http。
推奨される解決策: カルマ
Karmaを使用してテストを実行している場合(そうすべきです)、 ng-html2jsプリプロセッサを使用してテンプレートをロードするように構成できます。Ng-html2js は、指定した HTML ファイルを読み取り、$templateCache.
ステップ 1: でプリプロセッサを有効にして構成するkarma.conf.js
// karma.conf.js
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: "source/path/to/templates/.*/",
prependPrefix: "web/path/to/templates/",
// the name of the Angular module to create
moduleName: "my.templates"
},
アプリのスキャフォールディングにYeomanを使用している場合、この構成は機能します
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
preprocessors: {
'app/views/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'app/',
moduleName: 'my.templates'
},
ステップ 2: テストでモジュールを使用する
// my-test.js
beforeEach(module("my.templates")); // load new module containing templates
完全な例については、Angular テストの第一人者 Vojta Jina によるこの正規の例を参照してください。カルマ構成、テンプレート、テストなど、セットアップ全体が含まれています。
非カルマ ソリューション
なんらかの理由で Karma を使用せず (私はレガシー アプリのビルド プロセスに柔軟性がありませんでした)、ブラウザーでテストしているだけの$httpBackend場合、生の XHR を使用して実際のテンプレートをフェッチすることで、ngMock によるテイクオーバーを回避できることがわかりました。に挿入し$templateCacheます。このソリューションは柔軟性がはるかに劣りますが、今のところ作業は完了しています。
// my-test.js
// Make template available to unit tests without Karma
//
// Disclaimer: Not using Karma may result in bad karma.
beforeEach(inject(function($templateCache) {
var directiveTemplate = null;
var req = new XMLHttpRequest();
req.onload = function() {
directiveTemplate = this.responseText;
};
// Note that the relative path may be different from your unit test HTML file.
// Using `false` as the third parameter to open() makes the operation synchronous.
// Gentle reminder that boolean parameters are not the best API choice.
req.open("get", "../../partials/directiveTemplate.html", false);
req.send();
$templateCache.put("partials/directiveTemplate.html", directiveTemplate);
}));
しかし、真剣に。カルマを使用します。セットアップには少し手間がかかりますが、コマンド ラインから一度に複数のブラウザーですべてのテストを実行できます。そのため、継続的インテグレーション システムの一部として使用したり、エディターからのショートカット キーにしたりできます。alt-tab-refresh-ad-infinitum よりもはるかに優れています。