我正在尝试使用量角器进行测试以计算表中的行数。我正在测试的页面上有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);
});


我发现实际上没有任何元素通过filter函数。当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/

10-11 03:02
查看更多