Angular e2e测试检查元素列表

时间:2013-10-02 14:39:44

标签: angularjs karma-runner angularjs-e2e

我的情况如下 - 我有一个简单的页面列出了可用的产品:

<ul class="products ng-scope" id="products">
  <!-- ngRepeat: tag in products -->
  <li ng-repeat="product in products" class="ng-scope">
    <a ng-href="/#/viewProduct/1" class="ng-binding" href="/#/viewProduct/1">Product A</a>
  </li><li ng-repeat="product in products" class="ng-scope">
    <a ng-href="/#/viewProduct/2" class="ng-binding" href="/#/viewProduct/2">Product B</a>
  </li><li ng-repeat="product in products" class="ng-scope">
    <a ng-href="/#/viewProduct/3" class="ng-binding" href="/#/viewProduct/3">Product C</a>
  </li><li ng-repeat="product in products" class="ng-scope">
    <a ng-href="/#/viewProduct/4" class="ng-binding" href="/#/viewProduct/4">Product D</a>
  </li><li ng-repeat="product in products" class="ng-scope">
    <a ng-href="/#/viewProduct/5" class="ng-binding" href="/#/viewProduct/5">Product E</a>
  </li>
</ul>

在我的角度场景中,我想测试产品列表是否等于预期。我知道它可以/应该是一个单元测试,但假设我想要一个e2e测试。

阅读官方文档(http://docs.angularjs.org/guide/dev_guide.e2e-testing - 通常覆盖10%的主题)并调试角度代码后,我设法编写了以下测试:

'use strict';

describe('my app', function() {
  var productsList = [
    'Product A',
    'Product B',
    'Product C',
    'Product D',
    'Product E'
  ];

  it('should list all products', function() {
    browser().navigateTo('/#/products');
    var foundProducts = element('#products li').query(function(elements, done) {
      var productsArray = [];
      elements.each(function(index) {
        productsArray.push(elements[index].innerText);
      });

      done(null, productsArray);
    });

    expect(foundProducts).toEqual(productsList);
  });
});

任何人都可以告诉我如何更轻松地完成这项工作?

第二个问题,为什么元素[index] .text()是未定义的 - 实际上这是一个如何从元素[index]中传出jQuery对象的问题。

1 个答案:

答案 0 :(得分:4)

找到解决方案:

describe('my app', function() {
  var productsList = [
    ['Product A'],
    ['Product B'],
    ['Product C'],
    ['Product D'],
    ['Product E']
  ];

  it('should list all products', function() {
    browser().navigateTo('/#/products');

    expect(repeater('#products li').count()).toEqual(productsList.length);

    for (var i = 0; i < productsList.length; i++) {
      expect(repeater('#products li').row(i)).toEqual(productsList[i]);
    }

  });
});