我如何对数组进行断言并且仅在验证所有值后没有匹配项时才失败

How do I Assert against an Array and failing only if there is no match after all the values were verified

我正在使用 NightwatchJs 框架进行测试。我需要将实际值与一组有效值进行比较。但是,当在预期结果数组中找到正确的值时,我当前的实现会引发多次失败。我想显示测试的输出,只有当没有值匹配或测试通过时。


鉴于我有以下数组:

var topDesktop = [['728', '90'], ['970', '250'], ['970', '90'], ['980', '250'], ['980', '240'], ['980', '120'], ['980', '90'], ['1000', '90'], ['1000', '300']];

我想知道当前值是否在允许值范围内(topDesktop 数组)。

var actual = result.toString();
    for(var i = 0; i < topDesktop.length; i++){
      client.assert.equal(actual, topDesktop[i]);
    }

显而易见的输出是 for 循环的结果:

✔ Passed [equal]: 728,90 == [ '728', '90' ]
✖ Failed [equal]: ('728,90' == [ '970', '250' ])  - expected "970,250" but got: "728,90"
✖ Failed [equal]: ('728,90' == [ '970', '90' ])  - expected "970,90" but got: "728,90"
✖ Failed [equal]: ('728,90' == [ '980', '250' ])  - expected "980,250" but got: "728,90"
.
.
.

我想避免的是每次比赛尝试都失败。有什么好主意吗?

如果我没理解错的话,您想知道实际值是否在预期值之一内。如果是这样,您可以执行以下操作:

var actual = result.toString();
var isFound = false;
for(var i = 0; i < topDesktop.length; i++) {
    if(actual == topDesktop[i]) {
        isFound = true;
        break;
    }
}
client.assert.equal(isFound, true);

像这样,如果找到了值,就不会继续检查,因为break会停止for循环,最后你会检查是否找到了值。

过滤出你想要的元素。确保至少存在一个

client.assert(topDesktop.filter(e => actual == e).length > 0)