首页 > 解决方案 > 无法从函数内部访问数组变量

问题描述

我对 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);" 之前 被执行。请建议任何人。提前致谢。

标签: typescriptprotractor

解决方案


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

切换到异步/等待

您应该考虑切换到 async / await 测试。这将使 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());
}

推荐阅读