Alien Bishop Alien Bishop - 3 months ago 18
Node.js Question

How to unit test a tool that uses command-line-args

I'm using mocha to write unit tests for a tool that uses the command-line-args npm module. Unfortunately, the options intended for mocha are picked up by command-line-args in my tool, which dutifully throws an error if those options don't exist in my tool. For example, if I do this...

mocha --watch

...then command-line-args throws this:

UNKNOWN_OPTION: Unknown option: --watch

I can work around the problem by doing something like this in my tool...

var cli = commandLineArgs([
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'timeout', alias: 't', type: Number },
{ name: 'watch'} // So I can do mocha --watch

...but then
says my tool has a
option that it doesn't really have. And of course this gets out of hand if I want to pass more options to mocha.

What's the best way to "tell" command-line-args to ignore options in my scenario?


You should break your tool into a core part that takes in a configuration object and a command-line wrapper that uses that core part. Then you just unit test the core part.

Your aim really should be to test the core part, which is the part you've written; and not to exercise/test the command-line-args module, which in theory you should trust as being already proven to be working by its author.