柴-断言数组中的所有元素都等于一个给定的值,用

问题描述 投票:1回答:2

我有这个字符串数组。

[ "apple", "apple", "apple", "apple", "apple", "apple", ]

能否用Chai来做一个断言 数组中的所有元素都等于某个值?

arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple", ]
expectedFruit = "apple"

expect(arrayFromApiResponse).to ??? 

我需要测试数组中的每个值 arrayFromApiResponse"apple"

我发现这个 https:/github.comchaijsChai-Things

好像有了这个库就可以这样实现。

expect(arrayFromApiResponse).should.all.be.a(expectedFruit)

但是否可以在没有额外的库的情况下实现呢?也许我可以对 arrayFromApiResponse 好让柴哥来验证?

更新了。我已经更新了问题的标题,以防止我的问题被标记为重复,参考这种类型的问题。检查数组的所有值是否相等

javascript automated-tests chai
2个回答
1
投票

你可以使用 every() 方法。

const arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple", ]
const expectedFruit = "apple"

const allAreExpectedFruit = arrayFromApiResponse.every(x => x === expectedFruit);

console.log(allAreExpectedFruit);

1
投票
const arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple"]
const expectedFruit = "apple"

你可以用 filter() 但最有效的是老式的 for 循环。

function test(arr, val){
  for(let i=0; i<arrayFromApiResponse.length; i++){
    if(arr[i] !== val) {
      return false;
    }
  }

  return true;
}

这样做更有效率的原因是 这个函数一旦看到一个不等于预期值的值就会终止。其他函数会遍历整个数组,效率极低。像这样使用它。

expect(test(arrayFromApiResponse, expectedFruit)).toBe(true);
© www.soinside.com 2019 - 2024. All rights reserved.