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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With