2016-03-28 3 views
0

私はスパイしたいトリッキーな機能を持っています。sinonコントローラに存在するスパイ関数(this)

$rootScope.AlertsGlobal = {}; 

    this.updateHeight = function (clientHeight) { 
    $rootScope.AlertsGlobal.clientHeight = clientHeight; 

}; 

この関数はディレクティブコントローラ内部に住んでいると別のコントローラによって必要とされる(ユニットテストの差を必要と角度コントローラそう...

var GlobalAlertsController = function() { 
     this.updateHeight = function (clientHeight) { 
    $rootScope.AlertsGlobal.clientHeight = clientHeight; 
} 

var GlobalAlertsController = function() { 
} 

を指し?)。私はこのupdateHeightを(スパイsinonしようとした私のディレクティブ

html = angular.element("<my-directive> </my-directive") 
element = $compile(html)($rootScope) 
$rootScope.$digest(element) 
scope = element.scope() // note html and scope are defined below describe 

を嘲笑私のユニットテストの内部

require: 'MainGlobalAlerts', 

異なるいくつかの方法。

sinon.spy(scope, 'updateHeight') 

sinon.spy($rootScope, 'updateHeight') 

しかし、私のエラー文の

Typeerror: Attempted to wrap undefined property updateHeight as a function 

updateHeightが、私はそれをスパイすることができない場合は、このメソッドを呼び出す方法を確認していないこれで定義されているので。でcontrollerAs構文を使用し、$scope介してコントローラインスタンスに到達できるようにする

element = $compile('<my-directive>')($scope) 
var controllerInstance = element.controller('myDirective'); 
sinon.spy(controllerInstance, 'updateHeight'); 

答えて

1

コントローラインスタンス(this)は、このようなもので、controller method介して取得する必要があり、スコープに使用できません指令。通常のコントローラの利点の他に、より優れたテスト容易性を提供します。

+0

ありがとう、私は間違いなくこれを試してみます。私はコードがちょうどテストされた方法で制御できません – Winnemucca

関連する問題