1

I would like to write units tests for a CLI I made in inquirer. I want to verify that the prompts are displayed correctly, simulate choices in the command line, and verify that the resonses are correct.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Toli
  • 5,547
  • 8
  • 36
  • 56

1 Answers1

1

After trying a bunch of packages, reading SO, and making mocks, I found the answer!

First you need to make a testInquirer.js

import { writeFileSync, unlinkSync } from "fs";
import * as child_process from "child_process";

const TEMP_FILE_PATH = "/tmp/";

export default async (
  command,
  inputs,
  { output, error },
  { timeout, nodeScript, nodeCommand } = {
    timeout: 100,
    nodeScript: false,
    nodeCommand: "node"
  }
) =>
  new Promise(async resolve => {
    let proc;
    let tmpFile = `${TEMP_FILE_PATH}${Math.random()}.js`;

    if (nodeScript) {
      writeFileSync(tmpFile, command);
      proc = child_process.exec(`${nodeCommand} ${tmpFile}`);
    } else {
      proc = child_process.exec(command);
    }

    proc.stdout.on("data", data => {
      output(data);
    });

    proc.stderr.on("data", data => {
      error(data);
    });

    const sendKeys = async inputs => {
      await inputs.reduce(
        (previousPromise, input) =>
          new Promise(async resolve => {
            if (previousPromise) {
              await previousPromise;
            }

            setTimeout(() => {
              proc.stdin.write(input);
              resolve();
            }, timeout);
          }),
        null
      );

      proc.stdin.end();
    };

    await sendKeys(inputs);
    proc.on("exit", code => {
      if (nodeScript) {
        unlinkSync(tmpFile);
      }
      resolve(code);
    });
  });

// https://www.tldp.org/LDP/abs/html/escapingsection.html
export const DOWN = "\x1B\x5B\x42";
export const UP = "\x1B\x5B\x41";
export const ENTER = "\x0D";
export const SPACE = "\x20";

Then you can test your CLI as so.

The api for testInquirer is:

  • command: the command you use to run the CLI ('usually something like CDing into the right dir and running node . or yarn start)
  • inputs: array of inputs in order to send to stdin. You can use the exported helpers (ENTER, DOWN, etc) or enter input
  • output: pass a jest.fn() which will listen to all stdout output
  • opts:
    • timeout: timeout in between commands

test:

import run, { UP, DOWN, ENTER, SPACE } from '../testInquirer';

describe('cli', () => {
  it('runs', async () => {
    const outputMock = jest.fn();

    await run('yarn start', [
      // Choose "Babel Config Generator"
      SPACE,
      DOWN,

      // Choose "CodeFresh Config Generator"
      SPACE,

      // Next Question
      ENTER,

    ], outputMock);

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/Which Generators do you want to use/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/❯◯ Babel Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/❯◯ CodeFresh Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: Babel Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: CodeFresh Config Generator/)
    );
  })
})

If you want to test a file that accepts inputs into a function, it would look something like this:

describe(runGenerator, () => {
  let outputMock;
  let errorMock;

  beforeEach(() => {
    outputMock = jest.fn();
    errorMock = jest.fn();
  });

  it.only('runs a generator', async () => {
    const runGeneratorPath = `${__dirname.replace(/(\s+)/g, '\\$1')}/../runGenerator.ts`;
    const code = await testInquirer(`
      const runGenerator = require("${runGeneratorPath}").default;
      console.error(runGenerator)
      runGenerator(${JSON.stringify(MOCK_GENERATOR)});
    `, [], { output: outputMock, error: errorMock }, {
      nodeScript: true,
      nodeCommand: 'ts-node'
    });

    expect(code).toBe(0);

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: Mock Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/Executing step:/)
    );
  })
})
Toli
  • 5,547
  • 8
  • 36
  • 56