2013-12-09 78 views
5

我已經看到,以模擬在由指令產生的DOM用戶動作,有兩種方法,這兩種trigering事件的用戶動作:AngularJs:觸發事件,以模擬當單元測試指令

How to trigger ng-change in directive test in AngularJS

第一方法使用jQuery和第二個被叫browserTrigger角scenario.js定義的函數。第二個應該是更好的,因爲jQuery會觸發事件(我相信,我不爭論:))的錯誤。

使用angular-scenario意味着e2e爲我測試。但我看過egghead video,他似乎在做單元測試。這怎麼可能 ?

我猜他剛纔複製的功能?

我想我將測試指令作爲e2e測試,它更有意義,因爲單元測試更純粹的功能。


好吧,我剛剛發現browserTrigger是內部的東西不應該直接使用:https://github.com/angular/angular.js/issues/5178


謝謝!

+0

我試着要使用'ngScenario'來測試一個指令,並發現使用比使用手動觸發事件更復雜。也許我還沒有努力嘗試。無論如何,我已經使用jQuery進行了測試。你可以檢查出來[這裏](https://github.com/mbenford/ngTagsInput/blob/master/test/tags-input.spec.js)。希望他們能對你有用。 –

+0

[單元測試角度右鍵單擊指令]的可能重複(http://stackoverflow.com/questions/17720009/unit-test-angular-right-click-directive) –

回答

9

由於1.3.15可以使用triggerHandler觸發事件,如下圖所示,

it('should click the element',function(){ 
    element.triggerHandler('click') ; 
    expect($scope.clicked).toBe(true); 
}); 
+1

它也顯示在舊版本的同一頁版本 –

+0

是否可以模擬$ scope.function()調用? – Nimo

+0

我的意思是說'

'?出於某種原因,我絕對無法測試這種行爲...... – Nimo

1

簡單的工作,例如,在單元測試ENV:

spyOn(self, 'updateTransactionPrice'); 


var el = compile('<form name="form" latest novalidate json-schema="main.schema_discount" json-schema-model="main._data"><input type="text" ng-model="main._data.reverse_discount" ng-class="{ \'form-invalid\': form.reverse_discount.$invalid }" ng-change="main.transactionPrice(form);" name="reverse_discount" class="form-control-basic" placeholder="" ng-disabled="!main.selectedProduct.total_price"></form>')(scope); 
el.find('input').triggerHandler('change'); 

expect(self.updateTransactionPrice).toHaveBeenCalled();