Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the best way to unit test a commander cli? #1565

Closed
tiagoporto opened this issue Jul 9, 2021 · 4 comments
Closed

What is the best way to unit test a commander cli? #1565

tiagoporto opened this issue Jul 9, 2021 · 4 comments

Comments

@tiagoporto
Copy link

I would like to cover my cli (commander.js) with unit test.

What is the best way to do that?

@shadowspawn
Copy link
Collaborator

shadowspawn commented Jul 9, 2021

A couple of tips:

Have a function that creates a new Command object for your cli, so each test can use a fresh command.

If your tests include error cases detected by Commander, pass in some configuration when creating the command to make it easier to catch errors (.exitOverride()) or suppress output (configureOutput()).

@tiagoporto
Copy link
Author

@shadowspawn do you have some examples to share, will be really helpful?
Thank you

@shadowspawn
Copy link
Collaborator

shadowspawn commented Jul 14, 2021

Example of a function to create the "program", with some extra options for using in unit tests:

I am not claiming this is the best way, just what I used! TypeScript example:

// ------------------------------------------------------------------------------
// Command line processing. Returning new object to allow multiple calls for testing.

export function makeProgram(options?: { exitOverride?: boolean, suppressOutput?: boolean }): Command {
  const program = new commander.Command();

  // Configuration
  if (options?.exitOverride) {
    program.exitOverride();
  }
  if (options?.suppressOutput) {
    program.configureOutput({
      writeOut: () => {},
      writeErr: () => {}
    });
  }

...

@tiagoporto
Copy link
Author

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants