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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.