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.)
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
})