Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of script.aculo.us, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Freckle Time Tracking and Every Time Zone and write books like Retinafy.me.
   Want me to speak at your conference? Contact me!

BDD-style JavaScript testing

August 29th, 2006

Borrowing 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.