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

2024-04-28

我对 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("list text from drop list is " + text);”之前被处决。请推荐任何人。提前致谢。


这是因为.each方法从ElementArrayFinder返回一个承诺。看http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.each http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.each

切换到异步/等待

您应该考虑切换到异步/等待测试。这将使 Promise 更容易处理。您需要指定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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法从函数内部访问数组变量 的相关文章

随机推荐