最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jest expect to array contains element - Stack Overflow

programmeradmin6浏览0评论

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?

Share Improve this question asked Feb 3, 2021 at 17:19 RodrigoRodrigo 33113 gold badges72 silver badges157 bronze badges 3
  • 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 if id is in arrayOfIds"? – evolutionxbox Commented Feb 3, 2021 at 17:27
Add a ment  | 

2 Answers 2

Reset to default 16

Use .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');
发布评论

评论列表(0)

  1. 暂无评论