unit testing async-waterfall using mocha

2019-08-10 09:02发布

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
     });
};

2条回答
Animai°情兽
2楼-- · 2019-08-10 09:20

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?

查看更多
闹够了就滚
3楼-- · 2019-08-10 09:24

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');
});
};
查看更多
登录 后发表回答