Muirik
Muirik

Reputation: 6289

Simulating Command Line Entries For Node Tests

I am writing some tests for a Node/MongoDB project that runs various modules via command line entries. My question is, for the tests, is there a way I can simulate a command line entry? For instance, if what I write in the command line is:

TASK=run-comparison node server

... is there a way I can effectively simulate that within my tests?

Upvotes: 0

Views: 38

Answers (1)

angrykoala
angrykoala

Reputation: 4064

The common practice here as far as I know, is to wrap as much of your app as you can within a function/class where you pass the arguments, so you can easily test it with unit tests:

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

In your test file:

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

In your particular case, if all your tasks are set through env variables, through editing of process.env, mocks, or .env files you may be able to test that without modifications on your code.

If that is not enough for your case (i.e. you really need to exactly simulate command line execution) I wrote a small library to solve this exact issue some time ago: https://github.com/angrykoala/yerbamate (I'm not sure if there are other alternatives available now).

With the example you provided, A test case could be something like this:

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
});

In the end, this is a fairly simple wrapper of native child_process which you could also use to solve your problem by directly executing subprocesses.

Upvotes: 1

Related Questions