CLI Testing Library

3.0.1 · active · verified Wed Apr 22

CLI Testing Library provides a set of simple and complete utilities for testing command-line interface (CLI) applications, encouraging good testing practices by focusing on user interaction and observable output rather than internal implementation details. Inspired by the popular React Testing Library, it helps developers simulate user input and assert on console output (stdout, stderr). The library is currently at version 3.0.1, released in January 2025, and maintains an active development cadence with regular updates and major version bumps that introduce breaking changes and improvements. Its key differentiators include a focus on accessibility and user experience in tests, first-class TypeScript support, and integration with popular test runners like Jest and Vitest through dedicated extensions. It abstracts away the complexities of spawning and managing child processes, making CLI testing straightforward.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to render a Node.js CLI, simulate user interactions (arrow keys, enter), and assert on the console output using custom Jest matchers like `toBeInTheConsole`.

import { resolve } from 'path';
import { render } from 'cli-testing-library';
import 'cli-testing-library/jest'; // Extend Jest's expect with CLI matchers

describe('Interactive CLI Testing', () => {
  test('Should be able to make terminal input and view in-progress stdout', async () => {
    // Assuming a simple Node.js script that prompts for input
    const scriptPath = resolve(__dirname, './fixtures/stdio-inquirer.js');
    const { clear, findByText, queryByText, userEvent } = await render('node', [
      scriptPath,
    ]);

    // Wait for the first prompt to appear
    const initialPrompt = await findByText('First option');
    expect(initialPrompt).toBeInTheConsole();

    // Verify current selection
    expect(await findByText('❯ One')).toBeInTheConsole();

    // Clear console output for better readability in tests
    clear();

    // Simulate arrow down key press to select 'Two'
    userEvent('[ArrowDown]');

    // Verify new selection
    expect(await findByText('❯ Two')).toBeInTheConsole();
    clear();

    // Simulate Enter key press to confirm selection
    userEvent.keyboard('[Enter]');

    // Verify the final output after selection
    expect(await findByText('First option: Two')).toBeInTheConsole();
    expect(await queryByText('First option: Three')).not.toBeInTheConsole();

    // Optional: Clean up after the test if the CLI process persists
    // await cleanup();
  }, 10000); // Increase timeout for interactive CLI tests
});

view raw JSON →