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 验证?
更新:
我已经更新了问题标题,以防止将我的问题标记为与此类问题重复:
Check if all values of array are equal
您可以使用 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;
}
之所以更有效,是因为该函数会在发现不等于预期值的值时立即终止。其他函数将遍历整个数组,效率极低。像这样使用它:
expect(test(arrayFromApiResponse, expectedFruit)).toBe(true);
我有这个字符串数组:
[ "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 验证?
更新: 我已经更新了问题标题,以防止将我的问题标记为与此类问题重复: Check if all values of array are equal
您可以使用 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;
}
之所以更有效,是因为该函数会在发现不等于预期值的值时立即终止。其他函数将遍历整个数组,效率极低。像这样使用它:
expect(test(arrayFromApiResponse, expectedFruit)).toBe(true);