Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of the script.aculo.us user interface JavaScript library, a member of the Prototype core team and a Ruby on Rails core alumnus. You're using my work every day, even if you're not aware of it (sounds creepy, I know!). Need JS foo? Hire me.

BDD-style JavaScript testing

August 29th, 2006 by Thomas Fuchs, Comments Off

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.

Post to Twitter Tweet This Post Post to Digg Digg This Post Post to Facebook Share on Facebook

Comments Off

JavaScript Rocks! Peformance ebook
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.

Comments are closed.