0

I'm trying to add some mocha testing to a node module I have, but I'm new to it, and my lack of concreteness in terms of callbacks is hampering me. I have tried to pare things back to the most straightforward example, but it's still not working.

So my main.js is

var async = require('async');
var myObject = {};

myObject.test = function(params) {
   async.waterfall([
         async.apply(test, params)
      ],
      function(err, result){
         if (err) {
            console.log('Error: ' + err);
         } else {
            if (result === 200) {
               return result;
            }
         }
      });
};


function test(params, callback) {

   if(params) {
      callback(null, 200);
   }
}

module.exports = myObject;

Then my test file

var assert = require("assert");
var myObject = require('./main');

describe('test', function(){
   it("should return 200", function(done){
      myObject.test({test: 'such test'}, function(err, res) {
         if (err) return done(err);
         assert.equal(res, 200);
         done(res);
      });
   })
});

If I just run mocha it times out so I'm suspicious about that! Trying mocha --timeout 15000 also just stalls. Any direction you can provide would be really appreciated!

I got this far using this answer but can't get any further.


OK, I think I sorted it, but would still appreciate some feedback to see if I'm approaching it correctly, rather than just managing to get my test to pass.

var async = require('async');
    var myObject = {};

    myObject.test = function(params, callback) {
       async.waterfall([
             async.apply(test, params)
          ],
          function(err, result){
             if (err) {
                console.log('Error: ' + err);
             } else {
                if (result === 200) {
                   callback(result);
                }
             }
          });
    };


    function test(params, callback) {

       if(params) {
          callback(null, 200);
       }
    }

    module.exports = myObject;

and the test file is

var assert = require("assert"); var myObject = require('./main');

describe('test', function(){
   it("should return 200", function(done){
      myObject.test({test: 'such test'}, function(res) {
         assert.equal(res, 200);
         done();
      });
   })
});
Community
  • 1
  • 1
Philip O'Brien
  • 4,146
  • 10
  • 46
  • 96

1 Answers1

1

You fixed your main issue but your code still is broken. When you have an async method that takes a callback, you must always invoke the callback exactly once in all cases or your program's control flow will break. If you write an if/else clause, both branches must invoke the callback function. Both of your if statements above violate the callback contract. Check out understanding error-first-callbacks from The Node Way for a good explanation.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274