如何在将函数分配给javascript / mocha中的变量之前等待函数返回值

时间:2018-01-17 18:03:41

标签: javascript mocha

请看我的摩卡测试:

it.only('verify Lot in CFR List',function(done)){
this.timeout(20000);
var data = ui.cfrVerifyLot(); //calling cfrVerifyLot() method from another file
data.then(function(result) {
  console.log(result); // 'getting undefined' 'expecting success or failed'
  if(result=='success'){
    done();
  }
});
}

似乎ui.cfrVerifyLot()方法在完成自身之前分配返回值。 如何让它在完全结束之前等待分配结果。

这是我的cfrVerifyLot()函数:

cfrVerifyLot:function(){

    var result = '';
    const rest = require('./restAPI');
    const puppeteer = require('puppeteer');
    const assert = require('chai').assert;
    const cfg = require('../config-env.json');
    const objR = require('../obj-repo/obj-c.json');
    puppeteer.launch({
    //headless:false
}).then(async browser => {

    /*
    making some UI navigations
    */
    try{
    const innerText = await page.evaluate(() => document.querySelectorAll('some element name')[1].innerText);
    var str = innerText.substring(0,8);
    await page.waitFor(2*1000);
    if(str===input_lot_number){
      result = 'success'
      }          
    }
    catch(err){
      result = 'failed'  
    }
    finally{
      await browser.close();
      return result
    }
    });
},

1 个答案:

答案 0 :(得分:1)

您可以使用asyncawait运算符。

 it.only('verify Lot in CFR List',async function(done)){
    this.timeout(20000);
    var result = await ui.cfrVerifyLot();
      console.log(result); // 'getting undefined' 'expecting success or failed'
      if(result=='success'){
        done();
      }
    });
    }

修改 您的cfrVerifyLot函数returns没有价值。而是从result返回pupperteer。将puperteer's然后链更改为使用await,以便直接从函数返回result值。

cfrVerifyLot:async function(){

    var result = '';
    const rest = require('./restAPI');
    const puppeteer = require('puppeteer');
    const assert = require('chai').assert;
    const cfg = require('../config-env.json');
    const objR = require('../obj-repo/obj-c.json');
    let browser = await puppeteer.launch({//headless:false})
     /*
    making some UI navigations
    */
    try{
    const innerText = await page.evaluate(() => document.querySelectorAll('some element name')[1].innerText);
    var str = innerText.substring(0,8);
    await page.waitFor(2*1000);
    if(str===input_lot_number){
      result = 'success'
      }          
    }
    catch(err){
      result = 'failed'  
    }
    finally{
      await browser.close();
      return result
    }  
},