2016-06-29 9 views
4

$ elementを内部に持つ指令コントローラをテストする必要があります。だから私はこのような機能を持っている:

function func($event) { 
     $element.find('#la-la-la').focus(); 
} 

をし、テストでそれをレンダリング:

template = $compile(element)($scope); 
$scope.$apply(); 

controller = element.controller('myDirective'); 

そして、何私がやろうとしていることについて、そのコントローラの内部でこの機能をテストすることです指令。

describe('func method', function testFunc() { 
    it('should focus on element', function checkFocusing() { 
     controller.func(); 
     expect(focusSpy).toHaveBeenCalled(); 
    }); 
}); 

ここで、 "focusSpy"は模擬$要素サービス内のスパイです。 しかし、$ provide.service( '$ element'、...)を使うと、テストで見つけられないようです。それを$ scopeにインジェクトします。コンパイル前の$ elementは動作しません。ありがとうございました!

答えて

2

申し訳ありませんが、解決策を見つけました。 $ elementはディレクティブコントローラのプライベート変数なのでモックすることはできませんが、それはjQuery要素なので、jQuery自体のようにスパイすることができます:

describe('func method', function testFunc() { 
    it('should focus on element', function checkFocusing() { 
     spyOn($.fn, 'find').and.callThrough(); 
     spyOn($.fn, 'focus').and.callThrough(); 

     controller.func(); 

     expect($.fn.find).toHaveBeenCalledWith('#la-la-la'); 
     expect($.fn.focus).toHaveBeenCalled(); 
    }); 
}); 
関連する問題