コンテンツにスキップ

テストユーティリティ

Rune は、子プロセスを起動せずにコマンドをインプロセスでテストするための runCommand() を提供しています。@rune-cli/rune/test からインポートしてください。

import { runCommand } from "@rune-cli/rune/test";
import { expect, test } from "vitest";
import greeting from "../src/commands/index.ts";
test("greets by name", async () => {
const result = await runCommand(greeting, ["world"]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe("Hello, world!\n");
});

Rune のパース・実行パイプラインを通じてコマンドを実行します。入力は CLI トークンの string[] として渡されるため、argv パース、型変換、スキーマバリデーション、デフォルト値の処理がすべて実際の呼び出しと同様に動作します。

function runCommand(
command: DefinedCommand,
argv?: string[],
context?: RunCommandContext,
): Promise<CommandExecutionResult>
  • 型: DefinedCommand
  • 必須

defineCommand() で作成されたコマンド。

  • 型: string[]
  • デフォルト: []

コマンドに転送される CLI トークン。

  • 型: RunCommandContext
  • デフォルト: {}

省略可能な実行コンテキスト。

  • 型: string
  • 省略可能

ctx.cwd に注入されるワーキングディレクトリの値。process.cwd() は変更しません。

  • 型: number

プロセスの終了コード(成功時は 0)。

  • 型: string

キャプチャされた stdout 出力。

  • 型: string

キャプチャされた stderr 出力。

  • 型: CommandFailure | undefined

コマンドが失敗した場合の構造化されたエラー情報。

  • 型: unknown

コマンドが json: true を使用している場合の run() の戻り値。--json フラグの有無にかかわらず格納されます。--json が制御するのは主に output.info() の抑制であり、data のキャプチャには影響しません。

バリデーションエラーのテスト

Section titled “バリデーションエラーのテスト”
test("requires an id argument", async () => {
const result = await runCommand(command, []);
expect(result.exitCode).toBe(1);
expect(result.stderr).not.toBe("");
});
const command = defineCommand({
options: [{ name: "count", type: "number", default: 1 }],
run({ options, output }) {
output.info(`count=${options.count}`);
},
});
test("uses default count", async () => {
const result = await runCommand(command, []);
expect(result.stdout).toBe("count=1\n");
});
const command = defineCommand({
json: true,
run() {
return { items: [1, 2, 3] };
},
});
test("returns structured data", async () => {
const result = await runCommand(command, ["--json"]);
expect(result.data).toEqual({ items: [1, 2, 3] });
expect(result.stdout).toBe("");
});