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();
@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.
Neither
norare "falsy".– Pointy
Aug 25 at 13:37