How to Write Tests for CLI Tools in Node.js with CLI Mocker

Jordan McRae

Co-founder

2 min

Article Banner

If you've built a CLI tool in JavaScript or TypeScript, we created a simple library to help mock your CLI tool in your test suit. It works great with testing frameworks like Mocha and Jest.

One of the major challenges with writing tests for CLI tools is running and interacting with the tool itself. We wanted a simplified way to run our CLI tool, send it commands, and test interaction output in real-time, so we created CLI Mocker.

How it Works

The tool can be installed with either Yarn or NPM:

yarn add cli-mocker --dev or npm install cli-mocker --save-dev

Using it is fairly straightforward. Here's an example of how it would work in a Mocha test.

1import chai from 'chai';
2import {
3  run,
4  UP,
5  DOWN,
6  ENTER,
7  EXIT
8} = from 'cli-mocker';
9
10const { expect } = chai;
11
12describe('Test CLI', function() {
13  it('Runs', async () => {
14    const { output, lastOutput } = await run('npx my-cli-command', [
15      // Press down arrow key
16      DOWN,
17      // Press enter
18      ENTER,
19      // Press up arrow key
20      UP,
21      // Type something
22      'Hello, world!',
23      ENTER,
24      // Shut down CLI tool
25      EXIT
26    ]);
27    
28    return expect(lastOutput).to.equal(`Some value from your CLI tool's console.log() output`);
29  });
30});

CLI Mocker provides a few things out of the box. The first is a run method that starts up your CLI tool. It also provides a few helpful commands such as UP and DOWN, which simulates arrow key inputs, ENTER to simulate pressing the enter key, and an EXIT command to terminate the CLI tool and resolve the promise. Commands run synchronously, so the order of commands that you pass to the CLI Mocker is crucial.

The run method exposes an output, which is an array of everything displayed in the virtual terminal while your commands ran, and lastOutput which exposes the latest line of output from your tool.

Interacting directly with your tool can be extremely helpful for testing things such as:

  • Verifying that it runs in different Node environments
  • IO operations and expected outcomes
  • Conditional UX
  • Input validation

You can check out CLI Mocker on Github or NPM. If you run into any issues or would like to see new features, you can open a ticket on our Github issues page.