我之前已经发布了类似的问题,但想使其更加清晰和集中。所以我要在这里再写一次(还是应该继续编辑以前发布的内容?)

我正在使用量角器为angularJS编写e2e测试规范。

在量角器规格中,我也使用JavaScript。

问题是JavaScript计数器变量未按我的预期工作。

我将在这里向您显示代码:

// codes here within this describe block made me come back :( call this sample 1

//'use strict';

describe('list page ', function () {
    it('should list page', function () {

        browser.get('/list');

        var counterA = 0;

        element.all(by.repeater('page in pages')).each(function (page) {

            counterA++;
            //console.log(counterA);
        })

        //console.log(counterA);

        // Please be true assertion :(

        expect(counterA).toBeGreaterThan(0);
    })
});

// testing against protractor spec: wrote within the same js file. call this sample 2

bigitems = [["somevalue", "t", "y"], ["somevalue", "somevalue", "y"]];
counterB = 0;

for (smallitems in bigitems) {
    for (item in bigitems[smallitems]) {
        if (bigitems[smallitems][item] == "somevalue") { counterB++; }
    }
}

console.log(counterB)


我注意到的一件事是“示例2” counterB正在工作,并将“ 3”返回到控制台。但是,“样本1”在.each {}块外部为counterA返回0。

这是控制台输出。

Using the selenium server at http://localhost:4444/wd/hub
3
0
1
2
3
4
5
6
.

Finished in 11.877 seconds
1 test, 1 assertion, 0 failures


再次感谢您,以前每个人都帮助过我。

最佳答案

由于Javascript具有异步特性,因此您不能这样做。发生这种情况是因为Expect不等待element.all.each完成。

因此,您需要使用Promise使其起作用。但是这里的问题是element.all.each尚未返回诺言(至少尚未返回诺言,有关当前讨论,请参见here)。

有一些替代方法可以使其工作。

-如果您只想计算元素的数量,则可以简单地使用它。

it('sample', function() {
  element.all(by.repeater('page in pages'))
    .then(function(elements){
      return elements.length;
    })
    .then(function(count){
      //console.log("...." + count);
      expect(count).toBeGreaterThan(0);
  });
});


-或者只是这个。

it('sample', function() {
  expect(element.all(by.repeater('page in pages')).count()).toBeGreaterThan(0);
});


-如果您真的想手动进行计数,虽然您必须两次调用element.all,但您也可以使用此选项。

it('sample', function() {
  var count = 0;
  element.all(by.repeater('page in pages'))
  .then(function(){
    element.all(by.repeater('page in pages')).each(function(item){
      count++;
      //console.log(count);
    });
  })
  .then(function(){
    //console.log(count);
    expect(count).toBeGreaterThan(0);
  });
});


-或这个。

it('sample', function() {
  var counterA = 0;
  element.all(by.repeater('page in pages'))
    .then(function(elements){
      elements.forEach(function(entry){
        counterA++;
      });
    })
    .then(function(){
        //console.log(counterA);
        expect(counterA).toBeGreaterThan(0);
    });
});


-或者类似的。

it('sample', function() {
  element.all(by.repeater('page in pages'))
    .then(function(elements){
      var counterA = 0;
      elements.forEach(function(entry){
        counterA++;
      });
      return counterA;
    })
    .then(function(counterA){
        //console.log(counterA);
        expect(counterA).toBeGreaterThan(0);
    });
});


希望这可以帮助。

10-06 04:26
查看更多