javascriptnode.jsasynchronousrecursionvows

How to write a vows js bdd test for an asynchronous recursive operation


Code.js

var Util = function(){
    function factorial(n, callback){
        if(n == 1){
           return n;
        } else {
           return n*factorial(n-1, callback);
        }
        /*callback(returnValue); */ // Where should this line go?
    }

    return{
      factorial: factorial
    };
};

exports.Util = Util;

Test.js

var vows = require('vows'),
    assert = require('assert'),
    Util = require('./Code').Util;

var u = new Util();


vows.describe('Testing Utils').addBatch({
     'Test Factorial async':{
          topic: function(){
                u.factorial(5, this.callback);
           },
          'The output must be 120': function(result, ignore){
              assert.equal(result, 120);
           }
      }
}).run();

run on node.js

> node Test.js

I get the error callback not fired.

What I understand is just before my function returns if I am able to put this script: callback(computeValue); this should work IMHO. Please correct me If I am wrong. However, I do not understand where can I insert this. Thanks for your time!


Solution

  • First of all, your code isn't asynchronous, you need to use process.nextTick or setImmediate and, in the current situation the test case should look like I wrote below:

    code.js

    var Util = function () {
        this.factorial = function (n) {
            if (n == 1) {
                return n;
            } else {
                return n * this.factorial(n - 1);
            }
        }
    };
    
    exports.Util = Util;
    

    test.js

    var vows = require('vows'),
        assert = require('assert'),
        Util = require('./code').Util;
    
    vows.describe('Testing Utils').addBatch({
        'Test Factorial async': {
            topic: new Util,
            'The output must be 120': function (util) {
                assert.equal(util.factorial(5), 120);
            }
        }
    }).run();