如何使用 Jest 测试一个数组是否包含来自另一个数组的任何值?
How to test if an array contains any value from another array using Jest?
我有一个数组:
Const domesticAnimals = ['Chicken','lama','Donkey']
Const wildAnimals =['lama','lion','elephant']
如何测试 wildAnimals
是否列在 domesticAnimals
数组中?
我试过了
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
})
你实际上有两个数组:
const domesticAnimals = ['Chicken','lama','Donkey'];
const wildAnimals =['lama','lion','elephant'];
测试一个数组是否包含另一个数组的任何值的普通 JS 方法是:
domesticAnimals.some(domesticAnimal => wildAnimals.includes(domesticAnimal));
所以要将其放入测试中,将是:
test('test If any wild animal is in the domestic animal list', () =>{
expect(domesticAnimals.some(
domesticAnimal => wildAnimals.includes(domesticAnimal)
)).toBe(true);
});
作为 side-note,您将测试函数标记为 async
但实际上并没有 await
任何东西,因此 async
是多余的。
我有一个数组:
Const domesticAnimals = ['Chicken','lama','Donkey']
Const wildAnimals =['lama','lion','elephant']
如何测试 wildAnimals
是否列在 domesticAnimals
数组中?
我试过了
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
})
你实际上有两个数组:
const domesticAnimals = ['Chicken','lama','Donkey'];
const wildAnimals =['lama','lion','elephant'];
测试一个数组是否包含另一个数组的任何值的普通 JS 方法是:
domesticAnimals.some(domesticAnimal => wildAnimals.includes(domesticAnimal));
所以要将其放入测试中,将是:
test('test If any wild animal is in the domestic animal list', () =>{
expect(domesticAnimals.some(
domesticAnimal => wildAnimals.includes(domesticAnimal)
)).toBe(true);
});
作为 side-note,您将测试函数标记为 async
但实际上并没有 await
任何东西,因此 async
是多余的。