Testing schematics
@pbuilder/sdk/testing provides utilities for testing schematics with your test runner.
Bun is not required for the in-memory factory example below: it runs on Node with
Vitest, Jest, or Rstest.
Run your factory through runFactoryForTest, then assert on the resulting tree. This needs
no CLI or engine process, and no generated files land on disk.
A first test
Section titled “A first test”Start in a separate directory so this example does not change your application’s test
configuration. Use Node 26.8.1 and npm 11.19.0, the versions used to verify it.
Create this package.json, then install the SDK and Vitest:
{ "private": true, "type": "module"}Use a JavaScript ESM factory to keep the example independent of TypeScript transforms:
import { create } from '@pbuilder/sdk/commons';
export function greetingFactory(input) { create('src/greeting.txt', { template: `Hello, ${input.name}!\n`, options: {}, });}Create a tests directory and add:
import process from 'node:process';import { expect, test } from 'vitest';import { runFactoryForTest } from '@pbuilder/sdk/testing';import { greetingFactory } from '../factory.js';
test('commits a greeting through the SDK harness on Node without Bun', async () => { expect(process.versions.node).toBeDefined(); expect(process.versions.bun).toBeUndefined(); const result = await runFactoryForTest(greetingFactory, { name: 'Ada' }); expect(result.error).toBeUndefined(); expect(result.tree.get('src/greeting.txt')).toBe('Hello, Ada!\n');});import { defineConfig } from 'vitest/config';
export default defineConfig({ test: { environment: 'node', include: ['tests/vitest.test.js'] },});node node_modules/vitest/vitest.mjs runExpected result: one passing test. The greeting exists in the committed in-memory
tree, not as src/greeting.txt on disk. JavaScript interpolation produces the text;
this test does not exercise SDK template rendering.
Use Jest or Rstest instead
Section titled “Use Jest or Rstest instead”Keep the same package.json and factory.js. Copy the test above to the path for your
chosen runner and replace only its expect, test import; keep the other imports and
assertions unchanged. Install only the runner you choose. Each configuration selects
its own test file, so the three examples can also coexist.
In tests/jest.test.js, replace the Vitest import with:
import { expect, test } from '@jest/globals';export default { testEnvironment: 'node', testMatch: ['<rootDir>/tests/jest.test.js'], transform: {},};node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBandExpected result: one passing test. This uses Jest’s native ESM mode with transforms disabled; Node emits an experimental VM Modules warning.
Rstest
Section titled “Rstest”In tests/rstest.test.js, replace the Vitest import with:
import { expect, test } from '@rstest/core';import { defineConfig } from '@rstest/core';
export default defineConfig({ testEnvironment: 'node', include: ['tests/rstest.test.js'],});node node_modules/@rstest/core/bin/rstest.js runExpected result: one passing test, using the same factory and assertions.
Scope of the verified example
Section titled “Scope of the verified example”These versions passed the inline create case on Node 26.8.1 on macOS ARM64. The SDK
declares Node >=25.9.0 and Bun 1.3.14 in its engines; this result does not change those
requirements or establish official Node-only support for every SDK feature. Schema
validation, filesystem scaffolding, template rendering, and TypeScript type checking
are not covered by this example.
Runner references: Vitest configuration, Jest ESM, and Rstest configuration.
Read the result tree
Section titled “Read the result tree”result.tree is typed as ReadonlyMap<string, string> and is a Map at runtime,
not a plain object. Use .get(path) to read content (undefined when absent),
.has(path) to check membership, [...result.tree.keys()] to list paths, and
.size to count entries. Do not use result.tree[path] to read files.
Seed files and idempotence
Section titled “Seed files and idempotence”The seed option is a plain object (Record<string, string>); the returned
result.tree is a Map containing committed writes only, not a full workspace snapshot.
Seed files are readable by the factory, but untouched seed paths are absent from the
returned Map. A write to a seeded path appears when committed:
import { test, expect } from "vitest";import { runFactoryForTest } from "@pbuilder/sdk/testing";import { find, replaceContent } from "@pbuilder/sdk/commons";
test("a seeded file is readable; only the write is committed", async () => { const run = async (input: { name: string }) => { const existing = await find("services.txt").read(); replaceContent("services.txt", `${existing}\n${input.name}`); };
const seed = { "services.txt": "payments", "untouched.txt": "keep" }; const result = await runFactoryForTest(run, { name: "orders" }, { seed });
expect(result.error).toBeUndefined(); expect(result.tree.get("services.txt")).toEqual("payments\norders"); expect(result.tree.has("untouched.txt")).toBe(false);});packageDir — anchoring package-local verbs
Section titled “packageDir — anchoring package-local verbs”The options bag’s other field, packageDir (the schematic package’s absolute directory), anchors the
package-local verbs (scaffold, copyIn, create({ templateFile })) and opts the run
into schema-derived input validation against the adjacent schema.json. Without it those
verbs have nothing to resolve against. (When the CLI runs your schematic, it passes the
package location automatically, so this is only a testing concern. See
Scaffolding for the verbs themselves.)
Invoked children
Section titled “Invoked children”A factory that calls invoke needs its children in the test. Pass them in
the children option, keyed by the qualified name the factory invokes. This needs
@pbuilder/sdk 0.22.0 or later; the tests below pass with 0.23.0 and Vitest 5.0.0.
Each child is a ChildSchematic from @pbuilder/sdk/testing: its bare factory, an optional
packageDir to validate its inputs against its schema.json and declare its Result, and an
optional role. The harness runs each child on a fork of the run’s tree, as the engine does:
- A child that succeeds adds its edits to the run, and the parent receives its Result.
- A child that fails has its edits dropped, and the parent receives a
ChildFailedError. - A child with
role: "evaluation"returns its Findings, each with the child’s name assource, and its edits never join the run. - A name whose collection no child belongs to rejects with
UndeclaredCollectionError; a name of a known collection that has no child rejects withUnknownSchematicError. - The run holds at most 32 nested schematics, as under
builder execute.
Without children, every invoke rejects with InvokeUnavailableError
(this engine cannot invoke a child schematic; upgrade the Project Builder CLI).
import { expect, test } from "vitest";import { runFactoryForTest } from "@pbuilder/sdk/testing";import { ChildFailedError, create, invoke } from "@pbuilder/sdk/commons";
const addRoute = (input: { name: string }) => { create(`src/routes/${input.name}.ts`, { template: `export const path = '/${input.name}';\n`, options: {} });};
const addPage = async (input: { name: string }) => { create(`src/pages/${input.name}.ts`, { template: `export const title = '${input.name}';\n`, options: {} }); await invoke("default:add-route", { name: input.name });};
test("the child's files join the run", async () => { const result = await runFactoryForTest(addPage, { name: "about" }, { children: { "default:add-route": { factory: addRoute } }, });
expect(result.error).toBeUndefined(); expect([...result.tree.keys()].sort()).toEqual(["src/pages/about.ts", "src/routes/about.ts"]);});
test("an invoked evaluation returns its Findings and writes nothing", async () => { const review = () => { create("scratch.txt", { template: "x\n", options: {} }); return { items: [{ rule: "no-todo", message: "a TODO is left", severity: "warning" as const }] }; }; const report = async () => { const findings = await invoke("default:review"); create("reports/review.json", { template: JSON.stringify(findings), options: {} }); };
const result = await runFactoryForTest(report, {}, { children: { "default:review": { factory: review, role: "evaluation" } }, });
expect(result.error).toBeUndefined(); expect(result.tree.has("scratch.txt")).toBe(false); expect(result.tree.get("reports/review.json")).toBe( '{"items":[{"rule":"no-todo","message":"a TODO is left","severity":"warning","source":"default:review"}]}' );});To test an evaluation itself, without a parent, pass role: "evaluation" and name, the
qualified name its findings carry as source. result.result then holds its Findings. A test
that sets the role without name throws
runFactoryForTest: an evaluation factory needs options.name, the qualified name collection:schematic.
Netting and collisions in tests
Section titled “Netting and collisions in tests”The harness nets writes as the engine does. A create, copy, move or rename onto a path
the run created replaces it, and of two writes to one path the last one stays, whichever
schematic made them. A write onto a file of the workspace, a seed file in a test, without
{ force: true } is still a collision:
const writeIndex = () => { create("src/index.ts", { template: "export * from './child';\n", options: {} });};
test("the last claim on a path the run created wins", async () => { const parent = async () => { create("src/index.ts", { template: "export * from './parent';\n", options: {} }); await invoke("default:write-index"); };
const result = await runFactoryForTest(parent, {}, { children: { "default:write-index": { factory: writeIndex } }, });
expect(result.error).toBeUndefined(); expect(result.tree.get("src/index.ts")).toBe("export * from './child';\n");});
test("a create over a workspace file is still a collision", async () => { const parent = async () => { await invoke("default:write-index"); };
const result = await runFactoryForTest(parent, {}, { seed: { "src/index.ts": "export {};\n" }, children: { "default:write-index": { factory: writeIndex } }, });
expect(result.error).toBeInstanceOf(ChildFailedError); expect((result.error as ChildFailedError).reason).toBe("instruction-rejected"); expect((result.error as Error).message).toBe( 'the child schematic "default:write-index" failed (instruction-rejected): create failed at src/index.ts: path-collision' );});The four tests pass. A remove of a path that never existed, or that the run already deleted,
is rejected with not-found, as under builder execute; guard it with find(path).read().
The harness reports a failed child’s own message after the reason, as in the last test. Under
builder execute, the engine reports the same failure as
the engine rejected an instruction of the child (collision), and a failure it cannot classify
as the child schematic failed. See When an invoke fails.
What the harness does — and doesn’t — fake
Section titled “What the harness does — and doesn’t — fake”Templates are stored verbatim in the test tree. Rendering happens in the engine at
builder execute time, and the harness doesn’t fake it. So asserting on a templated
create means asserting on the raw {= .name =} text, not rendered output.
@pbuilder/sdk/testing ships 0.x, semver-exempt, until real use validates the result
shape.
Bun as an alternative
Section titled “Bun as an alternative”You can also use Bun’s test runner with the harness. Import test and expect from
bun:test in your Bun tests and run bun test with their path. The Node runtime
assertions above are specific to the Node smoke test; omit them when running on Bun.
Editor errors on bun:test?
Section titled “Editor errors on bun:test?”bun test strips types rather than checking them, so it runs fine either way, but your
editor needs a few tsconfig settings to resolve the imports. Add typescript and
@types/bun as dev dependencies, then make sure your tsconfig.json has:
moduleResolution: "NodeNext"(or"bundler"): TypeScript’s default legacy resolution cannot read a package’sexportsmap, which is the only route to@pbuilder/sdk’s subpaths (./testing,./commons, and friends). Without this, your editor reportsCannot find module '@pbuilder/sdk/commons'even though the import is correct.allowImportingTsExtensions: true: factories import the generated types with an explicit.tsextension (./schema.generated.ts), which TypeScript rejects by default.- If you restrict ambient types with
types, include"bun"alongside any existing entries so the editor can resolvebun:testfrom@types/bun.