Check that array does not contain falsy values in Jest

Viewed 1485

I am trying to create a unit test with Jest to make sure my array called values does not contain falsy values.

This for some reason does not work - the test passes:

const badValues = ['', null, undefined, false, {}, []];
expect(values).toEqual(expect.not.arrayContaining(badValues));

Below code works as expected (test fails), but surely there must be a proper way instead of looping over my values?

for (const value of values) {
  expect(value).toBeTruthy();
}
2 Answers

It is possible iterating over badValues and then includes() if values and badValues are both arrays of strings or numbers, not objects.

const badValues = ['', 'null', 'undefined', 'false', '{}', '[]'];

var values = [1,2,3,4,'null',5];


for(let i = 0; i<badValues.length; i++){

   if(values.includes(badValues[i])){
       console.log("bad value present");
       break;
   }

}

Otherwise, I think there is no better way than iterating over values. It could be possible using test() and regex, but [,],{,} are all special characters in regex expressions. So we should escape them.

May be this can work:

var isValid = arrayOfValuesToBeChecked.reduce(function(prev, elem) {
    // If elem is not truthy and if it is object, check its length 
    elem = elem ? typeof(elem) == 'object' ? elem instanceof Array ? elem.length : Object.keys(elem).length : elem : elem;
    return prev && elem;
}, true);
Related