typescript - 无法从函数内部访问数组变量
问题描述
我对 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
切换到异步/等待
您应该考虑切换到 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());
}
推荐阅读
- python - Github项目代码:工作目录问题
- reactjs - React - 从一个包更新另一个包中的组件的状态更改
- reactjs - 如何将道具从组件传递到 NextJS 中的 getServerSideProps()?
- ios - 如何使用 URLSession 在后台上传 zip 文件?
- python - 在 pandas read_csv() 中指定有序类别
- kubernetes - 如何用破折号设置环境?
- opengl - 纹理参数 GL_GENERATE_MIPMAP 是否只更新被更新的纹理区域?
- asp.net - 如何验证asp net core中的唯一属性
- python - 有没有办法检测两个文本是否与同一个品牌有关?
- c++ - 逐字节读取文件(C++)