簡體   English   中英

使用Mocha進行單元測試異步瀑布

[英]unit testing async-waterfall using mocha

我正在使用Mocha作為我的node.js應用程序的測試框架。

我有一個使用異步瀑布節點模塊的現有模塊,我正在嘗試為此編寫一個單元測試用例。 我無法為數組中的第二個功能編寫測試用例。 關於如何將一個函數的結果傳遞給數組中下一個函數的任何提示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
     });
};

我想我現在已經明白了這個問題。 在測試中-執行以下行:

user.resetPassword(request,response,next);

然后緊接着-行:

cryptoStub.restore();

問題是-async.waterfall將啟動第一個方法,但是在運行第二個方法之前,它將運行單元測試的下一行,因此您看不到下一個方法。 將解決它的代碼將類似於:

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

看起來好點嗎?

我的代碼如下。 我的問題是為這種方法編寫單元測試用例。 我正在將摩卡咖啡與sinon一起使用。 我寫的單元測試是

單元測試

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

resetPassword模塊

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM