Skip to content

Instantly share code, notes, and snippets.

@SpacyRicochet
Created October 4, 2011 20:05
Show Gist options
  • Save SpacyRicochet/1262643 to your computer and use it in GitHub Desktop.
Save SpacyRicochet/1262643 to your computer and use it in GitHub Desktop.
Unit test default initialization
BagOfTricks.Monster = SC.Record.extend(
/** @scope BagOfTricks.Monster.prototype */ {
name: SC.Record.attr(String, { defaultValue: 'Unspecified' }),
level: SC.Record.attr(Number, { defaultValue: 0 }),
keywords: SC.Record.attr(Array, { defaultValue: function() { return [ 'Unspecified' ] } })
}
);
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);
var defaultKeywordArray = ['Unspecified'];
equals(defaultKeywordArray, defaultMonster.get('keywords'));
}
);
@joewest
Copy link

joewest commented Oct 5, 2011

It fails because that's how javascript works. Here's a blog post that explains it in more depth and has some examples.

You can also just test this in your browsers console:

> [1] == [1]
false

> [1].sort().toString() == [1].sort().toString()
true

Long story short unit testing Arrays or non-String/Number Objects in javascript is a pain in the ass. It seems like the simplest path is what I originally recommended: serialize your objects and compare them as strings. Would love to hear about a different/better solution if you find one.

@SpacyRicochet
Copy link
Author

Well, at least it's definite that it's a pain in the ass, so thanks :) I'll stick to the toString() method for now. See you around in #sproutcore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment