ここには2つの指令と単体テストがあります。AngularJS:指令制限: 'E'はジャスミンユニットテストで呼び出される要素click()イベントを防止します
directive('myTestDirective', function() {
return {
link: function(scope, element, attrs) {
element.on("click", function(e) {
scope.clicked = true;
console.log("clicked");
}
}
});
とユニットテスト:
describe('my test directive', function() {
beforeEach(function() {
.....
inject($compile, $rootScope) {
scope = $rootScope.$new();
html = '<div my-test-directive></div>';
elem = angular.element(html);
compiled = $compile(elem);
compiled(scope);
scope.$digest();
}
});
it('should set clicked to true when click() is called', function() {
elem[0].click();
expect(scope.clicked).toBe(true);
});
});
上記単位テストが実行される
、テストパスとclicked
がコンソールに記録され
ここで最初の命令です。しかし、restrict: E
でこのディレクティブを検討
が追加さ:
directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
element.on("click", function(e) {
scope.clicked = true;
console.log("clicked");
}
}
});
とユニットテストを:
describe('my directive', function() {
beforeEach(function() {
.....
inject($compile, $rootScope) {
scope = $rootScope.$new();
html = '<my-directive></my-directive>';
elem = angular.element(html);
compiled = $compile(elem);
compiled(scope);
scope.$digest();
}
});
it('should set clicked to true when click() is called', function() {
elem[0].click();
expect(scope.clicked).toBe(true);
});
});
このテストが失敗しました。 clicked
はコンソールに記録されません。デバッグから私は指示にバインドされた関数click()
が実行されていないことがわかります。
restrict : 'E'
を引き続き使用しても、単体テストでのクリックをシミュレートする機能は維持できますか?
更新:私はMichal's plunkrのおかげで働いています。
私があると注入()関数を変更:この後
inject(function($compile, $rootScope, $document) {
scope = $rootScope.$new();
html = '<my-test-directive-element></my-test-directive-element>';
elem = angular.element(html);
$compile(elem)(scope);
scope.$digest();
});
、両方の属性を制限し、要素作業を制限用いてクリックします。
Plukrはここにある:(「クリック」)にjqLiteを使用して http://plnkr.co/edit/fgcKrYUEyCJAyqc4jj7P
あなたは異なる動作を参照していますあなたはhtmlコードになるので、内蔵された、あなたの中にディレクティブをngのクリックを使用して好む必要があります= '
'? –注入メソッドの内容を変更しようとします。 'scope = $ rootScope。$ new(); html = ' my-directive>'; compiled = $ compile(html)(scope); scope。$ digest(); ' –
tschiela
あなたの例に非常によく似た指示とテストで[Plunkr](http://plnkr.co/edit/VmQ3AyHxVxkU1ABt3WLS?p=preview)を作成しました。どちらのテストもシミュレートされたクリックでうまくいっています。あなたのテストが失敗していることを示すPlunkrを投稿できますか? –