簡體   English   中英

Chai - 斷言數組中的所有元素都等於給定值

[英]Chai - Assert that all elements in the array are equal to a given value with

我有這個字符串數組:

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

是否可以用 Chai 斷言數組中的所有元素都等於某個值?

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

expect(arrayFromApiResponse).to ??? 

我需要測試arrayFromApiResponse中的每個值都是"apple"

我發現了這個https://github.com/chaijs/Chai-Things

似乎有了這個庫,它可以像這樣完成:

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

但是是否有可能在沒有額外庫的情況下實現這一目標? 也許我可以對arrayFromApiResponse進行一些更改,以便 Chai 對其進行驗證?

UPD:我已更新問題標題,以防止將我的問題標記為與此類問題有關的重復問題: 檢查數組的所有值是否相等

您可以使用every()方法。

 const arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple", ] const expectedFruit = "apple" const allAreExpectedFruit = arrayFromApiResponse.every(x => x === expectedFruit); console.log(allAreExpectedFruit);

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;
}

這樣做更有效的原因是這個 function 將在它看到不等於預期值的值時立即終止。 其他函數會遍歷整個數組,效率極低。 像這樣使用它:

expect(test(arrayFromApiResponse, expectedFruit)).toBe(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM