BDD-style JavaScript testing
August 29th, 2006 by Thomas Fuchs, Comments OffBorrowing from Behaviour Driven Development techniques, especially the RSpec framework I’ve added some new features to script.aculo.us’ testing library.
It’s all about more readability, and even non-technical folk should be able to comprehend (at least some) of the tests. Let’s have a look:
1 2 3 4 5 6 7 8 9 |
Test.context("BDD-style testing",{ 'should automatically add extensions to strings': function(){ 'a'.shouldEqual('a'); 'a'.shouldNotEqual('b'); 'a'.shouldNotBeNull(); 'a'.shouldBeA(String); 'a'.shouldNotBeA(Number); } }); |
Basically, you’re defining a context for which one or more specifications should be asserted. Note the easy readability, and the added value by using a string to describe the test/specification, giving you the advantage of having better documentation for your JavaScript libraries.
Of course, setup and teardown is also supported, as are all normal assert* methods.
If you code in the Prototoypian way, with proper objects, an other added value, especially for higher-level behavioural specifications is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var testObj = { isNice: function(){ return true; }, isBroken: function(){ return false; } } // in Test.context 'should add object extensions': function(){ Object.extend(testObj, Test.BDDMethods); testObj.shouldBe('nice'); testObj.shouldNotBe('broken'); }, |
Note that the support for this is far from complete, and JavaScript has certain limitatons that won’t allow all the elegant solutions that are possible with Ruby, but your tests can get much cleaner this way.
For now, you’ll need the script.aculo.us version from the SVN trunk. For more examples, see the repository file browser: test file, test library.
Tweet This Post
Digg This Post
Share on Facebook








Do you run a web site or web application? Do your users a favor, and grab our ebook on JavaScript performance. Profit from our knowledge gathered in over 15 years of working with the Web and JavaScript and make your sites ultra-fast and your users ultra-happy.