Let's suppose that I have the following code:
const id = '1'
const arrayOfIds = ['1', '2', '3']
And I want to check if id
is in arrayOfIds
Something like this
expect(id).toBeIn(arrayOfIds)
How can I do this with Jest
?
Let's suppose that I have the following code:
const id = '1'
const arrayOfIds = ['1', '2', '3']
And I want to check if id
is in arrayOfIds
Something like this
expect(id).toBeIn(arrayOfIds)
How can I do this with Jest
?
-
1
Would
expect(arrayOfIds.includes(id)).toBe(true)
work? – evolutionxbox Commented Feb 3, 2021 at 17:21 - No, must be the contrary – Rodrigo Commented Feb 3, 2021 at 17:25
-
1
So,
toBe(false)
? But you asked "check ifid
is inarrayOfIds
"? – evolutionxbox Commented Feb 3, 2021 at 17:27
2 Answers
Reset to default 16Use .toContain
when you want to check that an item is in an array. For testing the items in the array, this uses ===, a strict equality check.
test('is id in arrayOfIds', () => {
const id = '1';
const arrayOfIds = ['1', '2', '3'];
expect(arrayOfIds).toContain(id);
});
expect(['a', 2, '3']).toContain(2);
expect(['a', 2, '3']).toContain('3');