javascript 量角器函数 returns 从黄瓜步骤定义调用时未定义,即使 console.log() 打印出正确的值

javascript protractor function returns undefined when called from a cucumber stepdefinition even though console.log()prints correct values

我正在为我的公司设计一个使用 Protractor-cucumber 的自动化框架。本框架使用的库如下:

  1. 量角器
  2. Cucumber-js
  3. Gulp
  4. Chai 如约而至

支持图书馆 1.量角器黄瓜框架


我的函数库包含所有可重复使用的UI交互函数,这些函数将在黄瓜步骤定义中调用。

有一个函数遍历 web-table,获取值并将其推入数组,如下所示。

fetchTableContentsToArray:async function(Page,ORString){
    let tableArray = []; //Blank array to store table data
    await element.all(by.css(##LOCATOR##)).each(async function(element){
        await element.getText().then(async function(value){
            await tableArray.push(value);
        });
    }).then(async function(){
        console.log(tableArray);
        return await tableArray;
    });
},

我已经在步骤定义文件中要求了具有此功能的文件,并且我能够调用此功能。但是在这样做时,函数内的 console.log() 语句将数组打印到控制台中,但是在将此函数调用到步骤定义文件中时,控制台打印未定义。不确定为什么函数 return 未定义而不是数组。

//Step definition of the cucumber step

let driver = require('Path to functions file');

Then(/^I check for new data on "([^"]*)" on "([^"]*)"$/,async function (element, page) {
    await driver.fetchTableContentsToArray(page,element).then(async function(val){
    console.log(val);
})

输出:

["test1",
 "test2"
 "test3"
 "test4"] // this is printed by console.log() inside the function
undefined //

我也尝试在黄瓜步骤定义中执行以下操作,但没有任何帮助。相反,它打印 Promise { } 并在解决承诺时打印 undefined.

Then(/^I check for new data on "([^"]*)" on "([^"]*)"$/,async function (element, page) {
    await driver.fetchTableContentsToArray(page,element).then(async function(val){
    console.log(val);
})

我已经尝试了所有组合,但仍然无法弄清楚问题所在。

欢迎任何帮助或纠正。提前致谢。

来自步骤定义文件的函数调用应在 promise 解析时打印 returned array/Object。enter code here

您正在使用 Async/Await 但您仍在使用 .then() 回调函数。也许这就是问题所在。

使用 Async/Await 你可以这样工作:

async function() {
 const val = await someFunctionWithPromise()
 console.log(val)
}

而不是:

function() {
 someFunctionWithPromise().then(funtion(val) {
  console.log(val)
 })
}
fetchTableContentsToArray: function(Page,ORString){
  return element.all(by.css(##LOCATOR##)).getText();
  // because getText() return a promise, unnecessary to use async/await
}

Then(/^I check for new data on "([^"]*)" on "([^"]*)"$/,async function (ele, page) {
    let val = await driver.fetchTableContentsToArray(page,ele);
    console.log(val);
    return val;
})

有基于您列出的技术的类似框架,尝试查看 github 存储库,也许您会得到线索 :)

https://thesoftwarehouse.github.io/Kakunin/docs/index.html