2

我想爲各種自定義的angularjs指令編寫unit和e2e測試,這些指令將javascript事件綁定添加到它們所連接的元素。AngularJS:如何在測試中調用事件處理程序並檢測綁定

在測試中,使用jQuery方法模擬click和dblclick事件很容易。

element("#id").click(); 

不過,我也綁定鼠標懸停,鼠標移開和文本菜單事件,並沒有找到一種方法在端對端測試調用這些。下面的代碼顯示了我正在採用的方法。

it('should show a context menu when the user right clicks on a grid row', 
    function() { 
    //not currently triggering the context menu 
    var outerRow = element(".ngRow", "outer row"); 
    var row = element(".ngRow:first > div", "row"); 
    angular.element(row).triggerHandler("contextmenu"); 
    expect(outerRow.attr("class")).toContain("open"); 
}); 

如何獲取contextmenu事件以在測試中觸發?

同樣,在指令的單元測試中,我希望能夠檢測事件綁定是否已附加到元素。

我怎樣才能做到這一點?

回答

4

到最後的底部。爲了觸發使用jQuery選擇的元素上的事件,顯然需要加載jQuery。問題是,正如here所解釋的那樣,Angular runner在沒有加載jQuery的IFrame中運行測試。

但是,您可以擴展角情景dsl以在加載jQuery的e2e測試環境中執行代碼。下面的功能,可以執行任何JavaScript方法,或發射任何事件:

//this function extends the Angular Scenario DSL to enable JQuery functions in e2e tests 
angular.scenario.dsl('jqFunction', function() { 
    return function (selector, functionName /*, args */) { 
     var args = Array.prototype.slice.call(arguments, 2); 
     return this.addFutureAction(functionName, function ($window, $document, done) { 
      var $ = $window.$; // jQuery inside the iframe 
      var elem = $(selector); 
      if (!elem.length) { 
       return done('Selector ' + selector + ' did not match any elements.'); 
      } 
      done(null, elem[functionName].apply(elem, args)); 
     }); 
    }; 
}); 

下面的代碼使用上述函數火在E2E測試contextmenu事件:

it('should show a context menu when the user right clicks on a grid row', function() { 
    var outerRow = element(".ngRow:first", "outer row"); 
    jqFunction(".ngRow:first > div", "contextmenu"); 
    expect(outerRow.attr("class")).toContain("open"); 
}); 
相關問題