首页 > 解决方案 > 当布尔结果为真时,ElementFinder.filter 函数不返回值

问题描述

我正在尝试使用量角器运行测试来计算表中的行数。我正在测试的页面有 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”,并为其他所有内容打印错误的声明。

如果我尝试调试并找出有多少元素通过过滤器函数:

// 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正确的表被传递并且答案是正确的。

有人可以解释为什么我的过滤功能不起作用吗?

标签: javascriptnode.jsprotractorcucumber

解决方案


添加一些代码以检查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)
})

推荐阅读