简体   繁体   English

检查数组是否在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. 我正在尝试使用Jest创建一个单元测试,以确保称为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. 如果valuesbadValues都是字符串或数字数组,而不是对象,则可以遍历badValues然后includes()

 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 . 否则,我认为没有比遍历values更好的方法了。 It could be possible using test() and regex, but [ , ] , { , } are all special characters in regex expressions. 使用test()和regex是可能的,但是[]{}在regex表达式中都是特殊字符。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM