Why does Jasmine toEqual return true when comparing empty array with empty object?

881 views Asked by At

I get why the following returns false...

expect({}).toBe({});

And I get why the following returns true...

expect({}).toEqual({});

But why is the following true?

expect([]).toEqual({});
1

There are 1 answers

0
Ben Coppock On BEST ANSWER

It appears that toEqual() is treating both items as objects and iterating over the enumerable properties of each — checking that their values are equal along the way.

In other words, it appears that it's treating the array as a regular JS object, using the index as the "property" that has a corresponding value. As long as the index/value pairs in your array match the property/value pairs in your object, jasmine apparently counts those as equal.

For example, the following is (surprisingly) successful…

  var myArray = ['a', 'b'];
  var myObj = {
    1: 'b',
    0: 'a'
  };
  expect(myArray).toEqual(myObj);