1

I'm trying to learn about unit testing and I found this overview by Ben Alman. On slide 23, he shows how a variable named actual containing an object {a: 1} is not equal to just the object itself. What does that mean? Aren't they the same value? How can the objects be different?

test("deepEqual", 7, function() {
  var actual = {a: 1};

  equal(    actual, {a: 1},   "fails because objects are different");
  deepEqual(actual, {a: 1},   "passes because objects are equivalent");
  deepEqual(actual, {a: "1"}, "fails because '1' !== 1");

  var a = $("body > *");
  var b = $("body").children();

  equal(    a,       b,       "fails because jQuery objects are different");
  deepEqual(a,       b,       "fails because jQuery objects are not equivalent");
  equal(    a.get(), b.get(), "fails because element arrays are different");
  deepEqual(a.get(), b.get(), "passes because element arrays are equivalent");
});
user2986242
  • 477
  • 1
  • 5
  • 19
  • 2
    Are you familiar with how `==` compares objects in JS (and indeed, most languages)? The answer follows immediately from that. – Chris Hayes Dec 01 '14 at 05:30
  • I'm sorry if this sounds dumb, but I don't really understand it. I'm reading about `==` vs `===` and I understand stuff like `new String("String")` == "String"` being true and `new String("String")` === "String"` being false. But with objects, it just makes no sense to me. I even did a `console.log(typeof actual);` to see if I was missing the type, but they're the same type. In another SO response, someone compared the objects to 2 sheets of blank paper. They're both paper (the `===`), but they're not the same paper (`==`) because the other {a: 1} is another instance of a newly created object. – user2986242 Dec 01 '14 at 06:09
  • Is that how I should think of it? – user2986242 Dec 01 '14 at 06:10
  • That's essentially the right way to think of it. `==` asks "are these the same object", not "do these two objects *look* identical". In the same way that newborn identical twins are not the same person, despite having all the same attributes, two objects are not equal even though they contain the same properties. – Chris Hayes Dec 01 '14 at 06:14

1 Answers1

0

Objects in JS are never the same even if their values appear to be. In mostly comes down to being different instances. Read more on Sameness in JavaScript. There are also much better answers on the real details on StackOverflow.

You can see how deepEqual determines an object's "sameness" here. Another good one to look at is lodash's implementation

Community
  • 1
  • 1
maxbeatty
  • 9,050
  • 3
  • 33
  • 36