1

So I have two objects

address: {
  id: 1234,
  city: "foo",
  country: "bar",
  name: "baz"
}

and

defaultAddress: { 
  id: 1234,
  city: "foo",
  country: "bar",
  firstName: "ba",
  lastName: "z"
}

If I try to do a straight up comparison / assertion between them, i.e.

expect(address).to.contain(defaultAddress)

(or the other way around), it'll fail because each contains fields the other does not

(AssertionError: expect {address} to have a property 'firstName')

I only want to comparing the values in the keys they both share. Is it possible to do something like that programmatically?

RagnarOdin
  • 42
  • 1
  • 6

2 Answers2

2

You're trying to match the objects on the subset of shared keys. This can be done as follows.

for(const key in address) {
  if(typeof defaultAddress[key] !== 'undefined') {
    expect(address[key]).to.equal(defaultAddress[key])
  }
}

Also have a look at this answer.

FK82
  • 4,907
  • 4
  • 29
  • 42
1

Why not use .to.include.any.keys as

expect(defaultAddress).to.include.any.keys(...Object.keys(address));

Didn't test though

Ijas Ameenudeen
  • 9,069
  • 3
  • 41
  • 54