0

I'm totally new to Chai, and this is probably really simple, but I can't find any reference to my case in the official docs. I'm trying to verify that an array with two objects has a property value exactly matching values in another array.

Consider the following:

test('Array includes ids', function() {
    const array1 = [
        {
            type: 'type1',
            id: '1'
        },
        {
            type: 'type2',
            id: '2'      
        },
    ]
        
    const array2 = ['1', '2']
    
    chai.expect(array1).to.have.deep.members(array2) // fails
})

I'd like to verify that objects in array1 has an id property with one of the values found in array2. I know I could map array1 as array1.map(p => p.id) and compare that with array2, but that seems to go against testing as a practice. After all, I don't want to tamper too much with my target to make it conform to my current level of knowledge.

Is there a better way to test this? (Needless to say, my example code above does not work as desired.)

conciliator
  • 6,078
  • 6
  • 41
  • 66
  • personally array1.map (p => p.id) seems to me to be the answer. On the other hand, what seems incorrect to me is the name of your test. I'm thinking of something like: Array elements include id. – Hugeen Nov 10 '21 at 06:12
  • I am not sure you can directly test via this. – Shubham Verma Nov 10 '21 at 06:14
  • can you please your error stack trace for more clarification of problem – Ashish Kamble Nov 10 '21 at 06:16
  • No need for stack trace, It's pretty obvious why it fails – Hugeen Nov 10 '21 at 06:20
  • Thank's for helping out folks. I did find a neat [answer](https://stackoverflow.com/a/45100356/182048). Unfortunately I'm using Postman and it seems they're not importing chai-like nor chai-things. So I guess I'll accept the current answer, although I'm not happy about the approach. – conciliator Nov 10 '21 at 07:37

1 Answers1

0

Just transform your array1 with .map() method to have your kind of array with only ids in it just like array2,

test('Array includes ids', function() {
    const array1 = [
        {
            type: 'type1',
            id: '1'
        },
        {
            type: 'type2',
            id: '2'      
        },
    ]
        
    const arr1 = array1.map(e=>e.id);//transform with .map() -> ['1', '2']
    const array2 = ['1', '2']
    
    chai.expect(arr1).to.have.deep.members(array2) // pass
})
Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29