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.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks

5 thoughts on “Inline.js – Inline Testing with Javascript

  1. I don’t care about this, now i’m making average 4500$ a month.
    There is tricky way i found on the internet. If you want to learn it too, just type in google: Ruthiezx’s method to
    earn online


Leave a reply to healthstyle.se Cancel reply


<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>