rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Create a runner#

createCliRunner(appOrCli, options?) from @rhythmjs/testing/cli wraps a Rhythm app that mounts a cli (or a bare RhythmCli) behind a single run(). Execution goes through the same toCliHandler as a real binary; nothing touches the process's actual stdio, argv, or exit code.

TypeScript
import { createCliRunner } from "@rhythmjs/testing/cli";

const runner = createCliRunner(cli);
const result = await runner.run("remote add origin https://x.git");
expect(result.stdout).toBe('added remote "origin" -> https://x.git\n');
expect(result.exitCode).toBe(0);

Run a command#

run(argv) accepts a command line as a string (trimmed and split on whitespace, so no quoted arguments) or as an argv array when arguments contain spaces. Flags are parsed by the cli's own withParsedArgv(), so --env=prod and boolean flags behave exactly as in production; without that middleware no flags are parsed. The result is { stdout, stderr, exitCode }: stdout and stderr are the captured text, newlines included.

TypeScript
const failed = await runner.run("fail");
expect(failed.stderr).toBe("error: boom\n");
expect(failed.exitCode).toBe(3); // fail(ctx, "boom", 3)

const unknown = await runner.run("nope");
expect(unknown.stderr).toBe("error: unknown command 'nope'\n");
expect(unknown.exitCode).toBe(2);

An unknown command exits with 2, a thrown error with 1, and fail(ctx, message, code) with your code. The runner is reusable: each run captures its own output.

Startup context#

Pass context to assign values onto every run's context. It is typed as a Partial of the app's startup context and input (minus the cli base fields), and it overrides values the app already holds, so a fake wins over a real one. For a bare cli it supplies the input the cli requires.

TypeScript
const runner = createCliRunner(app, { context: { db: fakeDb } });

The runner has no stdin. For commands that use withPrompt(...), give the prompt middleware your own IO to script the answers. There is no teardown(): close any resource the test created yourself in afterAll.