-
-
Save SpacyRicochet/1262643 to your computer and use it in GitHub Desktop.
| 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')); | |
| } | |
| ); |
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.
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.
The Array comparison test is going to fail because equals uses == to test equality.
If you want to do something kinda groddy you could cast them to Strings before comparing, like:
equals(defaultMonster.get('keywords').sort().toString(), defaultKeywordArray.sort().toString());But man, that doesn't feel very good.