模拟节点测试的命令行条目



我正在为一个通过命令行条目运行各种模块的Node/MongoDB项目编写一些测试。我的问题是,对于测试,有没有办法模拟命令行条目?例如,如果我在命令行中编写的内容是:

TASK=run-comparison node server

。有没有办法在我的测试中有效地模拟它?

据我所知,这里的常见做法是将尽可能多的应用程序包装在传递参数的函数/类中,以便您可以轻松地使用单元测试对其进行测试:

function myApp(args, env){
// My app code with given args and env variables
}

在测试文件中:

// Run app with given env variable
myApp("", { TASK: "run-comparison"});

在您的特定情况下,如果您的所有任务都是通过 env 变量设置的,通过编辑process.env、模拟或 .env 文件,您可以在不修改代码的情况下对其进行测试。

如果这对您的情况还不够(即您确实需要完全模拟命令行执行),我前段时间写了一个小库来解决这个确切的问题:https://github.com/angrykoala/yerbamate(我不确定现在是否有其他替代方案)。

使用您提供的示例,测试用例可以是这样的:

const yerbamate = require('yerbamate');
// Gets the package.json information
const pkg = yerbamate.loadPackage(module);
//Test the given command in the package.json root dir
yerbamate.run("TASK=run-comparison node server", pkg.dir, {}, function(code, out, errs) {
// This callback will be called once the script finished
if (!yerbamate.successCode(code)) console.log("Process exited with error code!");
if (errs.length > 0) console.log("Errors in process:" + errs.length);
console.log("Output: " + out[0]); // Stdoutput
});

最后,这是一个相当简单的本机child_process包装器,您也可以使用它通过直接执行子进程来解决问题。

最新更新