Search code examples
javascriptunit-testingequalssproutcore

Unit Test equals() fails when comparing two Arrays


The last Unit Test of in the following code fails, probably because the == operator, which is used by the equals(), doesn't compare the Arrays properly. However, I can't figure out why this happens.

Why does equals() fail when comparing an Array retrieved from an SC.Record to a newly instantiated Array?

monster_model.js

BagOfTricks.Monster = SC.Record.extend(
{
  name: SC.Record.attr(String, { defaultValue: 'Unspecified' }),
  level: SC.Record.attr(Number, { defaultValue: 0 }),
  keywords: SC.Record.attr(Array, { defaultValue: function() { return [ 'Unspecified' ] } })
}
);

monster_test.js

var defaultMonster;

module("BagOfTricks.Monster", {
    setup: function() {
        defaultMonster = BagOfTricks.store.createRecord( BagOfTricks.Monster, {} );
    },
    teardown: function() {
        BagOfTricks.store.reset();
    }
}
);

test("Default monster created as expected?", function() {
    equals(defaultMonster.get('name'), 'Unspecified');
    equals(defaultMonster.get('level'), 0);

    // The following test fails.
    var defaultKeywordArray = ['Unspecified'];
    equals(defaultKeywordArray, defaultMonster.get('keywords'));
}
);

Solution

  • JavaScript behaves quite strangely when it comes to comparing arrays. I can't tell you why, but I can tell you how to avoid it.

    Use the second function from Breaking Par: JavaScript Are Arrays Equal.

    It is type-safe and quite fast on large arrays.