在级联的promises中修改它时,如何在it块中修改本地定义的变量

时间:2015-07-18 10:34:08

标签: javascript selenium promise protractor

我想访问/修改级联多个promises中的it块的本地定义变量

像这样的东西

describe('make the app to fail',function(){
  it('should have error', function(){
    var canYouModifyMe = 0;
    anArrayofAlertElements.count().then(function(total){
      anArrayofAlertElements.get(0).isDisplayed().then(function(value){
        canYouModifyMe = 'yes'; // proven that it goes here
      });
    });
    console.log(canYouModifyMe); // Here's the problem, this is still 0. Im expecting it to be "yes"
  });
})

我已经在onPrepare函数中移动了变量(使其全局可访问,但不起作用) 如何在级联承诺中修改it块中的本地定义变量?

如果您需要更详细的代码,请查看以下代码。

// html file
// different errors
<div class="alert alert-warning" ng-show="data.error" >
{{(data.message)}}
</div>
<div class="alert alert-warning" ng-show="cart.error" >
{{cart.message}} 
</div>
...
- some other error goes here -


// page object 
function Util() {
  this.getAlertMessages = function(){
    return element.all(by.css('.alert'));
  }

  this.expectAlertMessages = function(){
    var that = this;
    var errorCount = 0; 
    this.getAlertMessages().count().then(function(count){          
      for(i=0;i<count;i++){    
that.getAlertMessages().get(i).isDisplayed().then(function(data){
          // for debugging purposes, lets make it always true so it increments error count
          data = true;           
          if (data===true) {
            errorCount++; // here is the problem. it doesnt increment the above defined variable "errorCount"
          }             
        });
      }
      return errorCount; // this is still 0
    }).then(function(obj){
      // errorCount still 0, that is supposedly 1
      expect(errorCount).toBeGreaterThan(0);
    });
  }
}

总之,我只想测试是否显示任何警告信息。

我坚持这一点,希望有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

这里的问题是我们正在谈论promisesasync执行。

当然,当您打印canYouModifyMe的值时,callback的{​​{1}}来自您修改值的promise未执行。尝试下面的代码,看看执行顺序是不同的:

describe('make the app to fail',function(){
  it('should have error', function(done){
    var canYouModifyMe = 0;
    anArrayofAlertElements.count().then(function(total){
      anArrayofAlertElements.get(0).isDisplayed().then(function(value){
        canYouModifyMe = 'yes'; // proven that it goes here
        console.log('Inside callback. Current value is', canYouModifyMe);
        done();
      });
    });
    console.log('Current value is', canYouModifyMe); // Here's the problem, this is still 0. Im expecting it to be "yes"
  });
})

另外,您应该已经注意到上面代码中另一个done回调的使用情况。这是关于async执行和jasmine的另一个细节。基本上通过运行该回调,我们告诉testspec)它的执行已经完成。