1

I'm new to Unit Testing with karma/jasmine, and I am trying to test two objects of the same type, but with different values. Which means, same properties but with different values on each object, like this:

let myFirstObject: myType = {
    id: 1,
    name: "name1",
    //... some other properties, 
}

let mySecondObject: myType = {
    id: 2,
    name: "name2",
    //... some other properties, 
}

it('should be a true comparison', () => {
    expect(myFirstObject).toEqual(mySecondObject);
});

I want it to be true, because the type and the properties are equal (the structure is the same), although the values stored are different. But using jasmine .toEqual() only passes when both items are entirely equal (properties and values). How can I do this comparison of structure/type but not considering the values, in karma/jasmine?

(note: my project is in ionic/angularIO, if that matters)

Any ideas?

Saikat1529
  • 186
  • 12
Rafaelius
  • 45
  • 4

1 Answers1

0

Object.Keys(myFirstObject) will return an array of the keys as strings. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Why not just loop the array and check that the mySecondObject.hasOwnProperty(key)?

Object.keys(myFirstObject).map(key => {
   expect(mySecondObject.hasOwnProperty(key)).toBe(true)
})

EDIT: If you are using typescript, you could use an interface to check the objects against. Interface type check with Typescript

joshvito
  • 1,498
  • 18
  • 23
  • as a matter of fact, i am using typescript and interface! But your first piece of code already worked as a charm for what i needed, so i will accept it as correct answer. Thanks a lot! – Rafaelius Dec 07 '17 at 16:43