我正在使用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
内的函数编写单元测试。
答案 0 :(得分:0)
您可以在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对象。