简体   繁体   中英

unit testing async-waterfall using mocha

I am using Mocha as a testing framework for my node.js application.

I have an existing module that uses async-waterfall node module.I am trying to write a unit test case for it. I am unable to write a test case for the second function in the array. Any tips on how would I pass the result of one function to the next function in the array var async = require('async');

module.exports.resetPassword = function(req,res,next){
 async.waterfall([
  function(done){
    var token = do something;
    done(err,token);
  },
   function(token,done){
       //do some stuff
     res.status(200).send('success');
   },
    ]function(err){ 
     //send failure response
     });
};

I think I understand the issue now. In your test - you execute the line:

user.resetPassword(request,response,next);

And immediately after that - the line:

cryptoStub.restore();

The issue is - that async.waterfall will start the first method, but before it runs the second one, it will run the next line from the unit test, and therefore you don`t see the next method. Code that will solve it will be like:

user.resetPassword(request,response,function(err) {
    cryptoStub.restore();
    done();
});

Does it look better?

My code is as follows. My issue is around writing a unit test case for this method. I am using mocha along with sinon for stubbing. The unit test that I have written is

Unit Test

  it("Should return an error if there is an error in retrieving the user details from the db",function(done)
{
    request={
        body:{
            email:'test@test.com'

        }
    };

    var expectedMessageFromCrypto = '12121212121';
    var cryptoStub = sinon.stub(crypto, "randomBytes",function(err,callback){
        callback(null,expectedMessageFromCrypto);
    });

    user.resetPassword(request,response,next);

    cryptoStub.restore();
    done();
});
});

The resetPassword module

methods.exports.resetPassword = function (req, res, next) {
var token = null;
async.waterfall([
    function (done) {
        crypto.randomBytes(16, function (err, buf) {
        if(err){
            return res.status(400);
        }
        else{
            token = buf.toString('hex');
        }
        done(err, token);
        });
    },
    function (token, done) {            
    var user = getUserInformation(req.body.email);
        sendEmail(user, done);
    }
], function (err) {
    if (err) {
        logger.error('error in sending confirmation mail');
        return next(err);
    }        
    res.status(200).send('success');
});
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM