Check that array does not contain falsy values in Jest

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.


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





Neither nor are "falsy".
– Pointy
Aug 25 at 13:37







@Pointy You are half right. is not falsy, while is actually falsy. Try == false in your browser.
– K48
Aug 25 at 15:40





== false





Try ? alert("truthy") : alert("falsy") in your browser.
– Pointy
Aug 25 at 16:07


? alert("truthy") : alert("falsy")





is an empty array, and a reference to any object is always truthy. The == operator is not a good way to test that.
– Pointy
Aug 25 at 16:08


==




2 Answers
2



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


badValues


includes()


values


badValues




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.


values


test()


[


]







Comparing objects and arrays like that does not make any sense becase comparison like === or === alyways return false..includes wont work with them.
– Jan Ciołek
Aug 25 at 18:20


===


===


.includes





@JanCiolek Yes, that is true, I guessed op had strings. In your case there is no way iterating badvalues.
– Emeeus
Aug 25 at 19:09




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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

Node.js puppeteer - Use values from array in a loop to cycle through pages