Last Updated: February 25, 2016
·
1.172K
· flsusp

How to write vows nodejs tests with assynchronous topic

A simple vows test looks like this (from the vows docs):

vows.describe('Division by Zero').addBatch({
    'when dividing a number by zero': {
        topic: function () { return 42 / 0 },

        'we get Infinity': function (topic) {
            assert.equal (topic, Infinity);
        }
    }
}).export(module);

The topic is the function the is called to "return" the result to be tested. But what if the result is computed by an assynchronous call like this?

account.find(id).balance(function(balance) {
    // Now I have the 'balance', but what to do with this?
});

Well, the secret here is that the topic function can use a hidden object attribute named this.callback. This method receives two parameters: first is an error (can be null in case of success) and second the value to be tested. Example:

vows.describe('Reading account balance').addBatch({
    'when consulting balance of account 1': {
        topic: function () {
                var c = this.callback;
               account.find(1).balance(function(balance) {
                       c(null, balance);
                });
        },

        // Assuming the balance for account 1 is 100.
        'then balance equal 100': function (topic) {
            assert.equal (topic, 100);
        }
    }
}).export(module);