2

I have this array of strings:

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

Is it possible to make an assertion with Chai that all elements in the array are equal to the certain value?

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

expect(arrayFromApiResponse).to ??? 

I need to test that each value in the arrayFromApiResponse is "apple"

I found this https://github.com/chaijs/Chai-Things

Seems like with this library it can be accomplished like this:

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

But is it possible to achieve this without additional library? Maybe I can make some changes to arrayFromApiResponse so it can be validated by Chai?

UPD: I have updated the question title to prevent marking my question as duplicate with reference to this type of questions: Check if all values of array are equal

anotheruser
  • 582
  • 1
  • 7
  • 23
  • Does this answer your question? [Check if all values of array are equal](https://stackoverflow.com/questions/14832603/check-if-all-values-of-array-are-equal) – bill.gates Jun 02 '20 at 09:16

2 Answers2

1

You could use the every() method.

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

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

console.log(allAreExpectedFruit);
Daan
  • 2,680
  • 20
  • 39
1
const arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple"]
const expectedFruit = "apple"

You can do this with filter() but the most efficient would be a good old for loop:

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

  return true;
}

The reason this is more efficient is that this function will terminate as soon as it sees a value which doesn't equal the expected value. Other functions will traverse the entire array, which can be extremely inefficient. Use it like this:

expect(test(arrayFromApiResponse, expectedFruit)).toBe(true);
  • [`every()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) works exactly the same, it returns false as soon as it has found an element that returns false. This can be found under "Description". – Daan Jun 02 '20 at 11:53