我正在尝试使用 Protractor 运行测试来计算表中的行数。我正在测试的页面有 5 个已加载的表,这些表没有 Id 参数,但它们在各自的表标题行中确实有不同的名称。因此,我提取所有表格元素,然后使用一个函数进行过滤,该函数检查第一个标记行内的文本。
要提取行数,我使用与此类似的代码:
// Step definition - used in cucumber.
Given(/^the (\w+) table should have (\d+) rows$/,
async (tableName, expectedRowCount) => {
const parsedRowCount = Number.parseInt(expectedRowCount);
const actualRowCount =
await element
.$$('table')
.filter(async (elem, _) => {
const textValue = await elem.$$('th').first().getText();
console.log(`${textValue} = ${tableName} => ${textValue === tableName}`)
return textValue === tableName;
})
.first()
.$$('tr')
.count();
assert.strictEqual(actualRowCount, parsedRowCount);
});
运行时,console.log 会为我要打印的表打印“Account = Account => true”,并为其他所有内容打印 false 语句。
如果我尝试调试并找出有多少元素通过过滤器函数:
// Step definition - used in cucumber.
Given(/^the (\w+) table should have (\d+) rows$/,
async (tableName, expectedRowCount) => {
const parsedRowCount = Number.parseInt(expectedRowCount);
const actualRowCount =
await element
.$$("table"))
.filter(async (elem, _) => {
const textValue = await elem.$$('th').first().getText();
console.log(`${textValue} = ${tableName} => ${textValue === tableName}`)
return textValue === tableName;
})
.count();
assert.strictEqual(actualRowCount, parsedRowCount);
});
我发现实际上没有元素通过过滤函数。我不明白为什么没有元素被传递,当 console.log 清楚地显示我感兴趣的表的返回值将返回 true 时。如果不是传递元素参数而是传递索引参数(过滤器函数的第二个参数)以及诸如 index === 1
之类的条件,则正确的表将被传递并得到答案结果是正确的。
有人可以解释一下为什么我的过滤功能不起作用吗?
最佳答案
添加一些代码来检查表中是否有第th
。
.filter(async (elem, _) => {
const thCount = await elem.$$('th').count();
if(thCount > 0) {
console.log(`there are ${thCount} ths`);
const textValue = await elem.$$('th').first().getText();
console.log(`${textValue} = ${tableName} => ${textValue === tableName}`)
return textValue === tableName;
}
else {
console.log("there are 0 ths");
return false;
}
})
或者您可以添加catch()
来查看filter()
中发生的任何失败
.filter(async (elem, _) => {
const textValue = await elem.$$('th').first().getText();
console.log(`${textValue} = ${tableName} => ${textValue === tableName}`)
return textValue === tableName;
})
.count()
.catch(function(err){
console.log('error: ' + err)
})
关于javascript - 当 bool 结果为 true 时,ElementFinder.filter 函数不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917305/