How to test if an array contains any value from another array using Jest?

Viewed 563

I have an array:

   Const domesticAnimals = ['Chicken','lama','Donkey']
   Const wildAnimals =['lama','lion','elephant']

How do I test If any wildAnimals is listed in domesticAnimals array?

I have tried

test('test If any wild animal is in the domestic animal list', async() =>{
expect(domesticAnimals ).toContain('lama')
}) //works perfectly

test('test If any wild animal is in the domestic animal list', async() =>{
expect(domesticAnimals ).toContain(wildAnimals) // does not work
})
1 Answers

You actually have TWO arrays:

const domesticAnimals = ['Chicken','lama','Donkey'];
const wildAnimals =['lama','lion','elephant'];

The plain JS way of testing if one array contains any values from the other would be:

domesticAnimals.some(domesticAnimal => wildAnimals.includes(domesticAnimal));

So to put this in a test, would be:

test('test If any wild animal is in the domestic animal list', () =>{
    expect(domesticAnimals.some(
        domesticAnimal => wildAnimals.includes(domesticAnimal)
    )).toBe(true);
});

As a side-note, you marked the test functions as async but don't actually await anything, so the async is redundant.

Related