Testing
The package has no test helpers of its own. A test uses what the kit already has: the application takes its values as options, a run can be opened by hand, and a model is an interface.
The examples use bun test and the program of the earlier pages.
Choosing a level
Section titled “Choosing a level”| You test | Use |
|---|---|
| A command, from the command line to the exit code and the printed lines | an application with a captured io, and cli.run(argv) |
| A workflow | an application, and workflow.run(input) with a scripted model |
| A harness with its tools | a test run, and harness.run(request, options) with a scripted model |
| One tool | a test run, and harness.toolbox(run).execute(name, input) |
| One run component or one flow step | a run over a started container |
Test a rule about what the user sees at the command level: an exit code, a message, the order of two things.
A command
Section titled “A command”HarnessApplication.create takes what a test wants to replace:
| Option | What it replaces |
|---|---|
io |
Where the printed lines go |
instances |
The named values |
overrides |
What is registered under a name, a component or an instance, with an object the test gives |
cli.run gives the exit code.
test("summarize without a key is a usage error", async () => { const out: string[] = []; const err: string[] = [];
const app = await HarnessApplication.create({ components: [NotesCli, SummarizeCommand, ModelStep, SummarizeStep, PrintStep, SummaryHarness, ReadLinesTool, TextFile], io: { out: (line) => out.push(line), err: (line) => err.push(line) }, instances: { "notes:env": {} }, });
await app.start();
const cli = await app.resolve(NotesCli); const code = await cli.run(["summarize", "--file", "notes.txt", "--model", "some-model"]);
expect(code).toBe(ExitCode.USAGE); expect(err).toEqual(["notes summarize: OPENROUTER_API_KEY is not set"]); expect(out).toEqual([]);
await app.stop();});This works because the program prints through the io and reads the environment from a named value. A component that calls console.log or reads process.env itself cannot be tested this way.
A scripted model
Section titled “A scripted model”A model is an LlmAdapter, so a test can give a small one of its own. This one makes the tool calls it is given and then gives a fixed answer. It keeps the results of the calls for the test to read.
ScriptedLlm.ts
import type { LlmAdapter, LlmSession, LlmToolCall, LlmToolResult } from "@kerpetensh/harness-kit";
export class ScriptedLlm implements LlmAdapter { public readonly provider = "fake"; public readonly model = "scripted"; public readonly results: LlmToolResult[] = []; private readonly calls: readonly LlmToolCall[]; private readonly answer: unknown;
public constructor(calls: readonly LlmToolCall[], answer: unknown) { this.calls = calls; this.answer = answer; }
public start(): LlmSession { return { runTools: async (hooks) => { for (const call of this.calls) this.results.push(await hooks.runTool(call));
return { ok: true, steps: 1 }; }, finalize: async (_request, output) => ({ ok: true, value: output.parse(this.answer), usage: [] }), closingAnswer: async () => undefined, }; }}- It needs none of the model packages.
closingAnswergivesundefined, so the harness always asksfinalizefor the answer. A session must have the method; without itrunthrows before the first model call.- It skips what a real adapter does, such as the check of a call against the schema before the tool runs. The tool’s own check still runs.
A test run
Section titled “A test run”new Run(grant, setup) opens a run by hand. With test: true, a harness may run in it without a workflow.
Field of setup |
What it is |
|---|---|
test |
true marks the run of a test: a harness runs in it without a workflow. |
values |
The values its components read with @RunValue. |
container |
The container that builds the run components. Without one, the run holds only what it is given. |
The grant comes from a PermissionGroupSet. This one gives every permission:
const everything = new PermissionGroupSet({}).grant(PermissionGroupSet.ALL);run.give(Class, instance) gives the run a ready instance. The run never builds that class: it takes the instance as it is, builds nothing the instance’s class takes with @Use, and runs none of its hooks.
test("the harness reads the file and gives the summary", async () => { const run = new Run(everything, { test: true }).give(TextFile, new FixedFile());
const llm = new ScriptedLlm( [{ id: "call-1", name: "read_lines", input: { from: 1, count: 2 } }], { summary: "Two lines." }, );
const result = await new SummaryHarness().run("notes.txt", { llm, run, limits: { maxToolCalls: 5, stepDeadline: Date.now() + 5_000, finalizeDeadline: Date.now() + 10_000 }, now: Date.now, log, });
expect(result.value).toEqual({ summary: "Two lines." }); expect(result.partialReason).toBeUndefined(); expect(result.toolCalls).toBe(1); expect(llm.results[0]?.output).toBe("one\ntwo");});- The test names the run in the options of
harness.run, and builds the harness withnew. A harness that no container built makes its own tool objects the first time it runs. - A run without a container refuses every class it was not given, with an error that names the class.
logis a logger that does nothing:
const quiet = () => {};const log = { debug: quiet, info: quiet, warn: quiet };One tool
Section titled “One tool”harness.toolbox(run) gives the tools of the harness inside one run. execute(name, input) runs one as a tool call does and gives the outcome: { ok: true, output } or { ok: false, error }.
test("read_lines gives the lines and refuses a wrong input", async () => { const run = new Run(everything, { test: true }).give(TextFile, new FixedFile()); const toolbox = new SummaryHarness().toolbox(run);
expect(await toolbox.execute("read_lines", { from: 1, count: 2 })).toEqual({ ok: true, output: "one\ntwo" }); expect(await toolbox.execute("read_lines", { from: 0, count: 2 })).toMatchObject({ ok: false });});A grant can be written by hand to test what a tool does without a permission:
test("read_lines fails without the permission", async () => { const run = new Run({ group: "none", every: false, permissions: [] }, { test: true }); const outcome = await new SummaryHarness().toolbox(run).execute("read_lines", { from: 1, count: 2 });
expect(outcome).toEqual({ ok: false, error: 'read_lines failed: ReadLinesTool.file needs the capability text-file, which the permission group "none" does not give', });});A double in the container
Section titled “A double in the container”A double for a component is a subclass marked with the same name, listed in place of the original. A class and a subclass registered under one name are one component of a run, so every @Use of the original gets the double.
FixedFile.ts
import { Capability } from "@kerpetensh/harness-kit";import { TextFile } from "./TextFile";
@Capability({ name: "text-file", description: "A text file with two fixed lines.", permission: "files:read", scope: "run",})export class FixedFile extends TextFile { public override lines(): Promise<string[]> { return Promise.resolve(["one", "two"]); }}The double declares the same permission as its base class; another one throws when the class is defined.
test("the workflow runs with the double in place of the file", async () => { const app = await HarnessApplication.create({ components: [FixedFile, ReadLinesTool, SummaryHarness, SummaryStep, SummaryWorkflow], });
await app.start();
const llm = new ScriptedLlm( [{ id: "call-1", name: "read_lines", input: { from: 1, count: 2 } }], { summary: "Two lines." }, );
const workflow = await app.resolve(SummaryWorkflow);
expect(await workflow.run({ path: "unused.txt", llm, log })).toBe("Two lines."); expect(llm.results[0]?.output).toBe("one\ntwo");
await app.stop();});ReadLinesTool still says @Use(TextFile). The run builds FixedFile, because that is the class registered as capability:text-file.
A run component or a flow step
Section titled “A run component or a flow step”A run over a started container builds run components as a workflow’s run does.
| You want | Do this |
|---|---|
| A run component | run.ready(Class) gives the ready instance. |
| To call a flow step by hand | Do what the workflow does: run.prepare(step) first, then execute inside the run. Without prepare, a @Use field of the step throws. |
Take the step from the container and do not build it with new, so that its @Inject fields are set.
test("a run component and a flow step by hand", async () => { const app = await HarnessApplication.create({ components: [FixedFile, ReadLinesTool, SummaryHarness, SummaryStep, SummaryWorkflow], });
await app.start();
const run = new Run(everything, { container: app.container, test: true, values: { path: "unused.txt" } }); const file = await run.ready(TextFile);
expect(await file.lines(1, 2)).toEqual(["one", "two"]);
const step = await app.resolve(SummaryStep); const llm = new ScriptedLlm([], { summary: "Nothing read." });
await run.prepare(step);
const added = await RunScope.enter(run, () => step.execute({ path: "unused.txt", llm, log }));
expect(added).toEqual({ summary: "Nothing read." });
await app.stop();});Give the run every value its components read with @RunValue. A missing one throws when the field is read.
A scripted model of the AI SDK
Section titled “A scripted model of the AI SDK”To test with the kit’s real adapter and no network, give AiSdkAdapter a mock model of the AI SDK. MockLanguageModelV4 comes from ai/test. Each call of doGenerate is one answer of the model; this model answers every call with the same text.
test("the harness works with a scripted model of the AI SDK", async () => { const model = new MockLanguageModelV4({ provider: "test", modelId: "scripted", doGenerate: async () => ({ content: [{ type: "text", text: JSON.stringify({ summary: "From the mock." }) }], finishReason: { unified: "stop", raw: undefined }, usage: { inputTokens: { total: 1, noCache: undefined, cacheRead: undefined, cacheWrite: undefined }, outputTokens: { total: 1, text: undefined, reasoning: undefined }, }, warnings: [], }), });
const llm = new AiSdkAdapter({ model, provider: "anthropic", modelId: "scripted", maxRetries: 0 }); const run = new Run(everything, { test: true }).give(TextFile, new FixedFile());
const result = await new SummaryHarness().run("notes.txt", { llm, run, limits: { stepDeadline: Date.now() + 5_000, finalizeDeadline: Date.now() + 10_000 }, now: Date.now, log, });
expect(result.value).toEqual({ summary: "From the mock." }); expect(model.doGenerateCalls.length).toBe(2);});- The model is called twice: once in the tool phase, where it calls no tool, and once for the final answer.
- A tool call is a content part of type
tool-callwith atoolCallId, atoolNameand the input as a JSON string, in an answer whose finish reason istool-calls. - The shape of a mock answer belongs to the AI SDK and changes with the SDK’s version.
What the tests of this page import
Section titled “What the tests of this page import”import { expect, test } from "bun:test";import { ExitCode, HarnessApplication, PermissionGroupSet, Run, RunScope } from "@kerpetensh/harness-kit";import { AiSdkAdapter } from "@kerpetensh/harness-kit/ai-sdk";import { MockLanguageModelV4 } from "ai/test";Run the tests from the project directory, so that Bun reads the decorator setting of its tsconfig.json; see TypeScript settings.