量角器-难以从承诺中返回价值

时间:2018-07-23 20:20:16

标签: javascript selenium protractor

我知道我的问题是我的诺言没有按照我期望的顺序执行,但是我是Protractor的新手,并希望这里的某个人能够友好地指出我的(可能很简单)错误。我有一个构建两个数组的测试,我想返回这两个数组,然后在本地设置它们,以便在其他测试中使用它们。问题是那两个数组返回未定义。这是我的第一篇文章,所以请放轻松。如果我张贴的不正确,请告诉我,我会予以纠正。

这是我在日志中得到的: “返回之前索引数组的大小:5 “ ARRAY.VALUE1:未定义” “ ARRAY.VALUE2:未定义”

以下是相关代码:

it('Build list of existing downloaded files and parse out index', function(){
        myPage.listExistingFiles(fileArray).then(function(array){
        console.log("ARRAY.VALUE1: " + typeof(array.value1));
        console.log("ARRAY.VALUE2: " + typeof(array.value2));
        indexArray = array.value1;
        existingFiles = array.value2;
    });
 });


 this.listExistingFiles = function(fileArray){
  var deferred = protractor.promise.defer();
  var existingFiles = [];
  var indexArray = [];
  glob(fileArray, function (err, files){
    if(err) throw err;
    // Build an array of indexes of existing files
    if(typeof files !== 'undefined' && files.length > 0){
      console.log("Verifying downloads... ");
      files.forEach(function (item, index, array){
        console.log("item: " + item);
        var fileNameArray = item.split(/[-.]/);
        // The index in the file name starts at one, so subtract 1 to get true index
        var fileIndex = (parseInt(fileNameArray[fileNameArray.length - 2]) - 1);
        console.log("fileIndex: " + fileIndex + " type: " + typeof(fileIndex));
        indexArray.push(fileIndex);
        existingFiles.push(item);
      });
    }
    console.log("Size of Index Array before RETURN: " + indexArray.length);
  deferred.fulfill(value1=indexArray, value2=existingFiles);
  });
  return deferred.promise;
}

1 个答案:

答案 0 :(得分:0)

您可以只创建一个对象并将其附加到deffered.fullfil中: (请使用此代码反映代码中的逻辑) 这是您的操作方法。

angularHomePage.po.js:

 var AngularHomepage = function() {
 this.listExistingFiles=function(){
  var deferred = protractor.promise.defer();
  var existingFiles = [];
  var indexArray = [];
   indexArray.push('fileIndex1');
    existingFiles.push('item1');
   indexArray.push('fileIndex');
   existingFiles.push('item');
    obj= {
        value1:indexArray,
        value2:indexArray
    }

console.log("Size of Index Array before RETURN: " + indexArray.length);

 deferred.fulfill(obj);
 return deferred.promise;
 }
}
 module.exports = new AngularHomepage()

和您的测试文件:

var angularHomepage =require('./../pageobjects/angularHomePage.po.js');
  describe('angularjs homepage',  function() {
   it('should greet the named user', function() {
   angularHomepage.listExistingFiles().then(function(array){
    console.log("ARRAY.VALUE1: " + typeof(array.value1));
    console.log("ARRAY.VALUE2: " + typeof(array.value2));
    indexArray = array.value1;
    existingFiles = array.value2;
    console.log(indexArray)
    });
   });
 });