簡體   English   中英

javascript 量角器函數在從黃瓜 stepdefinition 調用時返回 undefined 即使 console.log() 打印正確的值

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

我正在為我的公司設計一個使用 Protractor-cucumber 的自動化框架。 本框架中使用的庫如下:

  1. 量角器
  2. 黃瓜js
  3. 吞咽
  4. 柴如許

支持庫 1. Protractor-cucumber-framework


我的函數庫具有所有可重用的 UI 交互函數,這些函數將在黃瓜步驟定義中調用。

有一個函數可以遍歷網絡表,獲取值並將其推送到數組中,如下所示。

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() 語句會將數組打印到控制台中,但是在將此函數調用到步驟定義文件中時,控制台會打印 undefined。 不知道為什么函數會返回 undefined 而不是數組。

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

我已經嘗試了所有組合,但仍然無法安靜地找出問題所在。

歡迎任何幫助或糾正。 提前致謝。

步驟定義文件中的函數調用應在承諾解析時打印返回的數組/對象。 enter code here

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

您正在使用 Async/Await,但您仍在使用 .then() 回調函數。 也許這就是問題所在。

使用 Async/Await,您可以這樣工作:

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

代替:

function() {
 someFunctionWithPromise().then(funtion(val) {
  console.log(val)
 })
}

有基於您列出的技術的類似框架,請嘗試查看 github 存儲庫中的內容,也許您會有所了解 :)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM