0

I am trying to create an assertion method that the objects in question contain only scalar values (i.e., simple values like strings or numbers). It is OK to use JSON.stringify().

Example PASSED:

var expected = {foo: 5, bar: 6};
var actual = {foo: 5, bar: 6}
objectAssert(actual, expected, 'detects that two objects are equal');
// console output:
// passed

Example FAILED:

var expected = {foo: 6, bar: 5};
var actual = {foo: 5, bar: 6}
objectAssert(actual, expected, 'detects that two objects are equal');
// console output:
// FAILED [my test] Expected {"foo":6,"bar":5}, but got {"foo":5,"bar":6}

Here's my function so far:

function objectAssert(actual, expected, testName) {

 if(actual !== expected){
    console.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" but got \"" + actual + "\"");
  } else {
    console.info( "SUCCESS [" + testName + "]");
  }
}

Any idea what am I missing here?

  • You can't use `===` or `!==` to compare the contents of objects. When it's comparing objects it just tests if they're at the same location in memory. – Barmar Jul 03 '17 at 09:44
  • "Any idea what am I missing here?" — What makes you think you are missing something? – Quentin Jul 03 '17 at 09:44
  • @Barmar `===` is Identity operation. it does not mean objects must be in same memory location. it means objects should be identical including there types. – Shanil Fernando Jul 03 '17 at 09:47
  • @ShanilFernando In the case of objects, if they're identical then they're at the same memory location. – Barmar Jul 03 '17 at 09:48
  • Strings and numbers are different, but object equality is by memory location. – Barmar Jul 03 '17 at 09:49
  • @Barmar Yes, you are correct. I was confused with `scalar values`. My apologize. – Shanil Fernando Jul 03 '17 at 10:04

2 Answers2

0

Using !== to compare objects is wrong. What I suggest is, like you mentioned in the question, using JSON.stringify to compare both objects.

Example:

function objectAssert(actual, expected, testName) {

    _actual = JSON.stringify(actual);
    _expected = JSON.stringify(expected);

    if(_actual != _expected)
      console.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" but got \"" + actual + "\"");
    else
      console.info( "SUCCESS [" + testName + "]");
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
0

You can compare the json string objects:

if(JSON.stringify(actual) !== JSON.stringify(expected)){
   console.error( "FAIL [" + testName + "] Expected \"" + JSON.stringify(expected) + ", \" but got \"" + JSON.stringify(actual) + "\"");
} else {
  console.info( "SUCCESS [" + testName + "]");
}
Peter
  • 27,590
  • 8
  • 64
  • 84
  • I've seen this recommendation elsewhere (even the duplicate I linked to), but I think it's wrong. There's no guarantee that the order of properties will be the same when you stringify two objects. – Barmar Jul 03 '17 at 09:50