我正在使用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
的res
和uploadHandler
。
如何在waterfall
中编写函数的单元测试。
您可以在uploadHandler
之前定义函数并稍后导出它们。通过这样做,您可以在测试中完全控制resignDocs
,uploadHandler
甚至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对象。