Search code examples
arraysnode.jsnightwatch.jsassertionsassertj

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


I am working on a test using NightwatchJs framework. I need to compare the actual value against a set of valid values. However my current implementation throws multiple failures while the correct value is found in the expected result array. I want to display the output of the test, only if NO value matches or if the test pass.


Given that I have the following array:

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

And I want to know if the current value is within the allowed values (topDesktop array).

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

The output for obvious reasons is the result of the for loop:

✔ 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"
.
.
.

What I like to avoid, is to have a failure per match attempt. Any brilliant idea?


Solution

  • If I understood correctly, you want to find out if the actual value, is in one of the expected values. If so, you can do the following:

    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);
    

    Like this, if the value is found, it won't continue checking, since the break will stop the for loop, and finally you will check if the value was found or not.