如何使用量角器访问ng-grid元素?

时间:2014-06-23 22:45:04

标签: protractor ng-grid angularjs-e2e

我想为使用ng-grid的页面编写量角器测试。 我没有看到有关如何做到这一点的任何文档。在我的页面上,我看到一个包含数据的网格,html看起来像这样:

<div class="gridStyle" 
     ng-grid="tenantsGridOptions" 
     ng-if="tenantsGridOptions != undefined" >
</div>

如何从量角器中找到此网格上的元素?

1 个答案:

答案 0 :(得分:3)

考虑使用Controller:

var app = angular.module('angularE2EExamples');
app.controller('GridCustomersController', function ($scope, $http) {
  $scope.customers = [{id: 1, name: 'Lissa Montrose', email: 'lissa@company.com', city: 'Washington', comment: ''},
                      {id: 2, name: 'Karri Lanze', email: 'karri@company.com', city: 'Dallas', comment: ''},
                      {id: 3, name: 'Michael Smith', email: 'michael@company.com', city: 'Berkeley', comment: ''},
                      {id: 4, name: 'Fred Tyler', email: 'fred@company.com', city: 'Washington', comment: ''}
                     ];

  $scope.gridCustomers = {
    data: 'customers',
    columnDefs: [{field: 'id', displayName: 'Id', width: 30},
                 {field: 'name', displayName: 'Name'},
                 {field: 'email', displayName: 'Email'},
                 {field: 'city', displayName: 'City'},
                 {field: 'comment', displayName: 'Comment', 
                  cellTemplate: '<input class="form-control input-sm" type="text" ng-input="COL_FIELD" ng-model="row.entity.comment" />'}
    ],
    enableCellSelection: true,
    enableRowSelection: false,
    enableCellEdit: true,
    enableColumnResize: true,
    enableColumnReordering: true,
    multiSelect: false,
    width: 'auto'
  };
});

关注HTML:

<div ng-controller="GridCustomersController">
  <div class="gridStyle" ng-grid="gridCustomers" style="height: 200px">
  </div>
</div>

访问ng-grid组件内部不同元素的一种非常有用的方法是使用by.binding('row.entity.<field>'),其中“field”是数据模型的关键。您需要按如下方式定义测试用例:

describe('Customer test cases.', function() {
  it('Should iterate all grid elements', function(){
    browser.get('http://localhost:9000/customers');
    element.all(by.binding('row.entity.id')).each(function(cell){
      browser.sleep(500);
      cell.click();
      cell.getText().then(function(text){
        console.log('Id: ' + text);
      });
    });
    element.all(by.binding('row.entity.name')).each(function(cell){
      browser.sleep(500);
      cell.click();
      cell.getText().then(function(name){
        console.log('Name: ' + name);
      });
    });
    element.all(by.model('row.entity.comment')).each(function(cell){
      browser.sleep(500);
      cell.click();
      cell.sendKeys('New customer.');
    });
    browser.sleep(2000);
  });
});

Plunker

中找到的控制器和HTML内容的源代码

在此示例中,我为最后一列定义了自定义模板。所以,我使用by.model('row.entity.<field>')来访问相应的元素。

this Git repository中提供了给定e2e测试的完整可运行示例。

希望它有所帮助。