Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that array does not contain falsy values in Jest

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

1 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.

like image 170
Emeeus Avatar answered Oct 21 '25 23:10

Emeeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!