Created
October 4, 2011 20:05
-
-
Save SpacyRicochet/1262643 to your computer and use it in GitHub Desktop.
Unit test default initialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' ] } }) | |
} | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); | |
} | |
); |
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.
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
Still unsure on why == actually fails then. What does it check? And what would be the normal routine for unit testing Arrays?
Comparing Strings seems to work fine, even though I instantiated those inline for the equality check.