CLI Testlab - Test Framework for Node.js CLIs

6.0.1 · active · verified Sun Apr 19

cli-testlab is a specialized test framework designed for Node.js command-line interface (CLI) applications. Currently at stable version 6.0.1, it provides a streamlined API for executing shell commands, capturing their standard output and error streams, and asserting on their content. Key features include the `execCommand` function, which integrates robust assertion capabilities for positive, negative, and error-based output checks, supporting both string and array inputs for comprehensive validation. It also facilitates the management of environment variables per command execution and offers a `FileTestHelper` class for automatic cleanup of test-generated files. This library differentiates itself by focusing specifically on the unique challenges of CLI testing, offering built-in utilities that abstract away common complexities like child process management and output parsing, making it simpler to write reliable and maintainable tests for CLI tools without relying on heavy general-purpose test runners for these specific tasks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic command execution, output assertions, error handling, and file management with automatic cleanup using `FileTestHelper` within a typical test suite.

import { execCommand, FileTestHelper } from 'cli-testlab';
import { promises as fs } from 'node:fs';
import { resolve } from 'node:path';

describe('My CLI application', () => {
  let fileHelper: FileTestHelper;

  beforeEach(() => {
    fileHelper = new FileTestHelper('temp-test-dir');
  });

  afterEach(async () => {
    await fileHelper.cleanup();
  });

  it('should report version correctly', async () => {
    // Assuming 'my-cli.js' is in the same directory as the test file for simplicity
    // In a real project, you might use 'path.resolve' to locate it.
    await execCommand('node my-cli.js --version', {
      expectedOutput: '1.0.0',
      baseDir: process.cwd() // Or the directory where my-cli.js resides
    });
  });

  it('should show an error for unknown commands', async () => {
    await execCommand('node my-cli.js unknown-command', {
      expectedErrorMessage: 'Unknown command',
      baseDir: process.cwd()
    });
  });

  it('should create a file and clean it up', async () => {
    const testFilePath = fileHelper.createFile('test.txt', 'hello world');
    // Assume your CLI has a command like 'my-cli.js process-file test.txt'
    await execCommand(`node my-cli.js process-file ${testFilePath}`, {
      expectedOutput: 'File processed'
    });
    // Verify the file exists before cleanup
    await expect(fs.access(resolve(fileHelper.tempDir, 'test.txt'))).resolves.toBeUndefined();
  });
});

view raw JSON →