首页 > 解决方案 > 模拟节点测试的命令行条目

问题描述

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

TASK=run-comparison node server

...有没有一种方法可以在我的测试中有效地模拟它?

标签: node.jsmongodb

解决方案


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

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包装器,您也可以使用它通过直接执行子流程来解决您的问题。


推荐阅读