CLI Mocker

Github
Jordan McRae

Co-founder

1 min

Article Banner

CLI Mocker

This mini utility is used to help mock your CLI tools when writing tests in frameworks like Mocha or Jest. It will spawn your CLI tool, and synchronously execute an array of predefined commands you provide like arrow/enter keys, text inputs, etc.

Install

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

Usage

1import { run } = from 'cli-mocker';
2
3const { output, lastOutput } = await run('npx my-cli-command', [/* COMMANDS */]);

Available Inputs and Commands

Commands run synchronously, so the order of the commands that you use matters. Currently, this library supports the following inputs:

Up arrow key

1import { UP } from 'cli-mocker';

Down arrow key

1import { DOWN } from 'cli-mocker';

Enter key

1import { ENTER } from 'cli-mocker';

Shut down CLI

1import { EXIT } from 'cli-mocker';

String inputs

You can pass any string argument to your cli. For example, filling in an input prompt with "hello, world!".

Example with Mocha

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

Contributing

Pull requests and feature requests are welcomed!

Husky is set up to run linting and formatting before commits.