【问题标题】:How to test if an array contains arrays? (Jest)如何测试数组是否包含数组? (笑话)
【发布时间】:2019-05-17 13:40:07
【问题描述】:

给定以下函数:

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

我想测试输出数组是否包含数组:

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

考虑到matchers,如何测试一个数组是否包含数组?

【问题讨论】:

  • 你可以自己检查数组,然后看看你的检查是不是true。像const condition = checkerArray.every(a => arrayOfArrays.some(array => ......)) 然后expect(condition).toBeTruthy()

标签: javascript jestjs npm-scripts react-scripts


【解决方案1】:

可能是这样的?

我们使用Array.isArray()(这里是docs)来测试每个元素

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

【讨论】:

    【解决方案2】:

    如果你使用 lodash 就很简单了

    _.any(arr,function(a){
        return Array.isArray(a);
    })
    

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 2013-08-26
      • 2015-10-16
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多