如何在Async.waterfall数组Node.js中

时间:2017-12-15 14:57:39

标签: javascript node.js unit-testing mocha

我正在使用Mocha编写测试用例,

这是我的代码的结构 -

var async = require('async');

const uploadHandler = (req, res) => {
  async.waterfall([
    function testdata(callback){
      fetchdetails(callback, req, res);
    },

    function resignDocs(callback) {
      //do something
      console.log(req.body.name);
    }
  ]);
};

app.post('/uploadfile', uploadHandler);
exports.server = app.listen(config.port, () => {
  console.log('info', `Listening for incoming connections on port ${config.port}...`);
});

我正在尝试编写函数testdata和函数resignDocs

的测试用例

我使用了

来获取文件
var app = require('../app')

(app.js是带有上述代码的文件名)

现在app.fetchdetails如果导出它,我就不能访问该功能。它也需要来自req的{​​{1}}和res

如何为uploadHandler内的函数编写单元测试。

1 个答案:

答案 0 :(得分:0)

您可以在uploadHandler之前定义您的功能,然后再导出它们。通过这样做,您可以在测试中完全控制resignDocsuploadHandler甚至uploadHandler

var async = require('async');

function testdata(callback) {
    fetchdetails(callback, req, res);
}

function resignDocs(callback) {
    //do something
    console.log(req.body.name);
}

const uploadHandler = (req, res) => {
    async.waterfall([
        testdata,
        resignDocs
    ]);
};

app.post('/uploadfile', uploadHandler);

exports.server = app.listen(config.port, () => {
    console.log('info', `Listening for incoming connections on port ${config.port}...`);
});

exports.testdata = testdata;
exports.resignDocs = resignDocs;
exports.uploadHandler = uploadHandler;

导出类似的函数后,您可以利用sinon-express-mock来模拟req和res对象。