如何在Async.waterfall数组Node.js中编写函数的单元测试

问题描述 投票:1回答:1

我正在使用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不允许我访问该功能。它也需要来自reqresuploadHandler

如何在waterfall中编写函数的单元测试。

javascript node.js unit-testing mocha
1个回答
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对象。

© www.soinside.com 2019 - 2024. All rights reserved.