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

How to modify the locally defined variable in the it block when modifying it in the cascaded promises

本文关键字:修改 何修改 变量 it 承诺 级联 定义      更新时间:2023-09-26

我想访问/修改级联多个承诺中的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函数中移动了变量(使其全局可访问,但不起作用)我如何修改一个局部定义的变量在它块级联的承诺?

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

// 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);
    });
  }
}

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

我被这个卡住了,希望这里有人能帮助我。

这里我们讨论的是promisesasync的执行。

显然,当您打印canYouModifyMe的值时,您修改值的promise中的callback没有执行。试试下面的代码,看看执行顺序是否不同:

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回调。这是asyncjasmine执行的另一个细节。基本上通过运行这个回调,我们告诉test (spec)它的执行已经完成。