ディレクティブ テストに慣れるために、以下に示す簡単な例を作成しました。残念ながら、テストは失敗しており、リンク関数が呼び出されていないようです。このディレクティブは、アプリ内で使用すると機能します。
message
属性をハードコーディングし、リンク関数内の条件を削除し、さらに $watch 内から属性セットを抽出しようとしましたが、テストはまだ失敗します。
このような他の投稿があり、その理由は $digest 呼び出しの欠如によるものでしたが、私はそれを持っていて、it
仕様ブロックに移動しようとしました.
呼び出しを実行するconsole.log(elem[0].otherHTML)
と、スコープバインディングが機能するようです
<wd-alert type="notice" message="O'Doole Rulz" class="ng-scope"></wd-alert>
私は何が欠けていますか?
alert.spec.js
"use strict";
describe('Alert Specs', function () {
var scope, elem;
beforeEach(module('myapp'));
beforeEach(inject(function ($compile, $rootScope) {
scope = $rootScope;
scope.msg = "O'Doole Rulz";
elem = angular.element('<wd-alert type="notice" message="{{msg}}"></wd-alert>');
$compile(elem)(scope);
scope.$digest();
}));
it('shows the message', function () {
expect(elem.text()).toContain("O'Doole Rulz");
});
});
アラート.js
angular.module('myapp').directive('wdAlert', function() {
return {
restrict: 'EA',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
attrs.$observe('message', function() {
if (attrs.message) {
element.text(attrs.message);
element.addClass(attrs.type);
}
})
}
}
});