无法从函数内部访问数组变量

时间:2019-01-23 19:28:34

标签: typescript protractor

我对TypeScript和量角器非常陌生,希望将所有从下拉列表中提取的值放入数组中,以便可以从另一页进行验证。

export class AdditionalCostPage extends BasePage {
  getAllUsageCategoryElements() {
    var usageCategory: string[] = [];

    element
      .all(
        by.xpath(
          "//p-dropdown[@name='usageCategory']/div/div[3]/div/ul/li[*]/span"
        )
      )
      .each(function(element, index) {
        element.getText().then(function(text) {
          console.log('list text from drop list  is ' + text);
          usageCategory.push(text);
        });
      });

    console.log('Size of the array is ' + usageCategory.length);
  }
}

结果,usageCategory的大小为0,我还注意到大小为0的打印在“ console.log(”下拉列表中的列表文本为“ + text);”之前。被执行。请建议任何人。提前致谢。

2 个答案:

答案 0 :(得分:0)

这是因为.each中的ElementArrayFinder方法返回了一个Promise。参见http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.each

切换到异步/等待状态

您应该考虑切换到异步/等待测试。这将使承诺更容易实现。您将需要在量角器配置中指定SELENIUM_PROMISE_MANAGER: false。 StackOverflow还提供了其他异步/等待测试示例。请记住,您需要等待每个异步方法。

// When adding in async to this method, by default it returns a Promise<void>.
async getAllUsageCategoryElements() {
  // Note: You should not use xpath as a selector since it makes
  // your tests brittle.
  // See Locator Strategies in http://www.protractortest.org/#/style-guide
  // Also nit: think about using "const" or "let" over "var".
  const usageCategory = element.all(
      by.xpath(
        "//p-dropdown[@name='usageCategory']/div/div[3]/div/ul/li[*]/span"
      );

  // Think about using fat arrows instead of "function"
  await usageCategory.each(async (element, index) => {
    const text = await element.getText();
    console.log('list text from drop list  is ' + text);
  });

  // You could push the ElementFinder object to an array and find the length
  // or you could get the count. See
  // http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.count
  console.log('Size of the array is ' + await usageCategory.count());
}

答案 1 :(得分:0)

问题是上述实现未正确处理异步。

Size of the array is 0
list text from drop list  is a
list text from drop list  is b
list text from drop list  is c
list text from drop list  is d

考虑使用await异步,这将使这些问题更加清晰。

async getAllUsageCategoryElements() {
    let usageCategory: string[] = [];

    const elms = await element
      .all(
        by.xpath(
          '//p-dropdown[@name='usageCategory']/div/div[3]/div/ul/li[*]/span'
        )
      );

    for (var i = 0; i < elms.length; i++) {
      usageCategory.push(await elms[i].getText());
    }

    return usageCategory;
}

您将从何处调用此函数

const abc = await getAllUsageCategoryElements();
console.log('Size of the array is ' + abc.length);