Read my book

I wrote books about Webpack and React. Check them out!

Wednesday, May 4, 2011

Runner Pattern for JavaScript

While developing chaining assert a bit further at GitHub I came by an interesting testing pattern I would like to share. I use it primarily for testing my assert statement. Pretty cyclic, eh?

The Pattern


The whole point of this pattern is that it just runs every method defined within a given Object, or rather a test set. Here's an abstract example of an Object definition:

A concrete definition might look something like this:


As you can see I provide some metadata (suite name, test names), set up data (_) and actual test methods. The idea is that "_" provides some predefined data passed to each method on invocation. The content of "_" may be accessed via "this".

This is not enough. We'll need some way to actually run the tests. Here's my test runner in its entirety. It's a bit verbose but hopefully gets to the point:


To keep the API simple I decided to overload "tests" function. It works both for registering tests and running them. In order to keep running versatile, I abstracted the way it deals with output. I simply return data formatted a certain way for the output callback and let it worry about how to show it. Here's a sample showing how this idea works out in practice:


You could take the idea further by outputting to many places at once, defining new sinks etc. It's possible to style the HTML output as well. Console output could be prettified by drawing it in color.

Conclusion


This pattern is quite specific to testing. I have no doubt there are tons of solutions like this out there. I just thought it might be something fun and simple to share. :)

If you want to see the pattern in action, take a look at jsassert.