Embed your unit tests in your source code.

Being able to add some tests for a component directly underneath its implementation feels oddly liberating. It's also pretty easy to set up. Suppose you have a a function countBears() with integrated test:

function countBears (animals) {
    return animals.filter(animal => animal === 'bear').length;

describe(countBears.name, function () {
    it('returns the amount of bears', function () {
        var animals = ['bear', 'fox', 'pig', 'bear'];
        require('assert').equal(countBears(animals), 2);

Running the tests embedded in your source code is pretty easy. Just feed Mocha your source tree, and it will find the describe and it statements.

To generate production code with the describe and it statements removed, we can write some simple Sweet.js macros:

macro describe {
    rule { ($x:expr (,) ...) } => { }

macro it {
    rule { ($x:expr (,) ...) } => { }

export describe;
export it;

These macro's will match your describe and it statements and replace them with nothing. Sweet.js plugins are available for pretty much any build tool, so just include them in your chain and you're all set!


I wrote an article introducing Minosse, a testing library we wrote, on the IceMobile tech blog:

When we started working on a new large project, consisting of a number of rest API's, we saw our chance to make a change. We decided to flip the process on its head. Instead of starting with writing features, we'd start by writing a library of common steps for testing REST API's. Then our testers would use, as much as possible, that library of existing steps. We named the library Minosse and open sourced it on Github.

The full article can be found here.


I've been putting this of, but it's time to write something about Virgilio. Virgilio is a pretty opinionated framework for building Node.js applications at the centre of a number of projects I've been involved in. Now I realize that 'framework' is a bit of a dirty word in the Node.js community, I think partly because it implies this huge block of monolithic code. It makes me proud that this is not the case for Virgilio, which has started small and now, a year later, has proven to be very resilient to function creep.

So, what are Virgilio's opinions then? Well, for starters is uses Promises (the amazing bluebird to be precise). And nope, not getting into that debate. Also, Virgilio uses one global configuration object which is shared with all the modules you define. And lastly, well, it kind of takes over managing the structure of your application from the filesystem.

Why? Because moving a function to another file and than having to update paths in a dozen of files is a pain. Because I'm not sure sure I want to write modular code if it means half of my lines are require statements. Because I don't care where my function lives. I just want to call it.

To me, it feels like Virgilio takes the same approach to managing functions that Gmail took to managing email: Before Gmail, I had this beautiful folder structure that once in a while I rebuilt completely because of some mails I could not fit in. Since I have Gmail I don't need that structure anymore. When I'm looking for a particular email I just use search. It's easier. With Virgilio it's the same thing. I can just call my function function and let Virgilio worry about where to find it.

In Virgilio you have to register your functions by passing them to a .defineAction$() call. This offer a number of interesting benefits, one of which is that each function can automatically be wrapped in bluebirds Promise.method() call. This ensures that when you call an action it will always return a promise, even if the function you defined returns an ordinary value or throws an error. It's a wonderful guarantee that takes away a source of confusion and bugs without forcing you to add a lot of boiler plate to simple synchronous code.

Another cool advantage of this approach, is that it allows you to easily extend a function with additional behaviour. For instance, suppose that you want to add memoization to a number of actions. Just write a plugin that hooks into the .defineAction$() call and adds it to any registration which contains a certain flag. Done.

One last example I'd like to give is the possibility to give each action a personalized context. For instance, Virgilio creates a bunyan child logger for each action, which adds the path of an action (it's namespaces and name) to each log entry. That's a piece of context you won't have to add to every single log call.

So that's Virgilio in a nutshell. Check it out on Github and let me know what you think!

Dead simple request validation

When you're building an API you'll write a lot of validation rules. Most of these rules are pretty dumb, checking property types and the like. Instead of writing a lot of code for these steps, you're probably using something like JSON Schema to keep your validation rules organised.

What follows is so stupidly simple I feel silly writing about it, but I haven't seen it before, so here it goes. Let's create a middleware that takes a JSON Schema to validate the entire request object.

//Using a restify server.
server.get('/foo', [

A simple schema that just checks a single header looks like this.

    "title": "root",
    "type": "object",
    "required": [ "headers" ],
    "properties": {
        "headers": {
            "type": "object",
            "required": [ "my-header" ],
            "properties": {
                "my-header": {
                    "type": "string",
                    "enum": ["foo", "bar"]

That's a lot of schema for a single property check, but as you're adding more and more rules this approach starts paying for itself quickly.

If validation fails, the server responds with a 400, but this is behaviour you can completely customize. The library can be found on NPM and has the beautiful name json-schema-validation-middleware.

Examples as tests

When writing a library, examples are often the best way to explain how it should be used. The problem with examples is that it is time consuming to keep them up to date, and non-working examples are a surefire way to annoy potential users.

For our framework Virgilio, I wanted to do better. Lets make our examples test cases, run them on every build, and we can be sure they always work. As a bonus, we'll get free tests. Nice. In theory this sounds great, but the harness test runners require will distract from what the examples aim to demonstrate. Wouldn't it be nice if we could write the example in a natural way and then parse it into a form that can be fed to mocha?

For this purpose specifically I wrote gulp-exemplary. It reads a very basic example format and outputs QUnit style test cases. For instance a console.log in the example, demonstrating the value of a variable at a certain point in the code, becomes an assertion in the test case:

console.log(typeof 42); //=> 'number'
// ... turns into ...
assert.deepEqual(typeof 42, 'number');

Start of line comments are interpreted as descriptions of test cases below. To support asynchronous code we're considering a test case done when the bottom most console.log (or assertion) in the test case is passed. It's all very simple, but so far it seems to cover our needs in the example writing department.

Virgilio has an examples directory which contains examples demonstrating every aspect of its functionality. Users can try them out, running them with the node command, using them as a starting point for experimenting with the framework. And because I test them as part of the build process, I know they'll work.