Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an array contains arrays? (Jest)

Given the following function:

chunk = (arr, n) => {
    return arr.reduce(function(p, cur, i) {
        (p[i/n|0] = p[i/n|0] || []).push(cur);
        return p;
    }, []);
}

I want to test if the output array contains arrays:

test("Splits a given array in N arrays", () => {
    let _input = Array.from({length: 999}, () => Math.floor(Math.random() * 999));;
    let int = mockService.getRandomArbitrary();
    expect(generalService.chunk(_input, int)).toContain(???????);
})

Considering matchers, how can one test if an array contains arrays?

like image 600
Ericson Willians Avatar asked Dec 07 '25 10:12

Ericson Willians


1 Answers

Possibly something like this?

We use Array.isArray() (docs here) to test each element

let output = generalService.chunk(_input, int));
let containArrays = true;
if (output.length) {
    output.forEach(element => {
        // containArrays is false if one of the element is *not* an array
        if (Array.isArray(element) === false) containArrays = false;
    });
}
// if output is an empty array it doesn't contain arrays
else containArrays = false;

expect(containArrays).toBeTruthy();
like image 73
chatnoir Avatar answered Dec 09 '25 23:12

chatnoir



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!