I just read an article by Sergi Mansilla, Extending JavaScript with inline unit tests, where he implements a pretty neat inline testing syntax using sweet.js, which allows writing code like this:

function square(n) {
    return n * n;
} where {
    square(2) is 4
    square(3) is 5

Obviously this isn’t really valid javascript – sweet.js is a javascript preprocessor which allows you to write macros in your code which are then rewritten as valid javascript. I liked the idea of being able to write inline tests, but wanted to be able to achieve it in pure js only, so I wrote inline, a little snippet of javascript (~20 lines) which implements this functionality. The syntax is a bit different, but I think it’s still pretty readable:

var square = function(n) {
    return n * n;
 .where(3) shouldEqual(5);

The way it works is simple. Inline adds a ‘where’ function to the prototype of Function, which returns an Inline object which records the function and the arguments and also has assertion functions (currently only shouldEqual() but it’s pretty obvious how more could be added).


– To use it with functions written like function fn() { ... } you must wrap the function declaration in brackets to avoid a syntax error: (function fn() { ... }).where(...).shouldEqual(...);
– Make sure not to call where() without following it with an assertion function as it’ll replace the original function! (ie. for the code: var fn = function() { ... }.where(...); fn will be an Inline object and not the specified function
– You can chain multiple where().shouldEqual()s on a function to run multiple tests

Inline.js is only a quick experiment, and I wouldn’t really recommend mixing tests and code, but I do think there’s something interesting about inline testing, and could see it being used for teaching or demonstration purposes. Sergi’s code definitely offers an advantage that as it’s written as a macro you can write the tests inline but strip them out for production.