/directive:testing-directive-codefrom directive
Tests Directive modules and systems using createTestSystem, mockResolver, assertFact, assertDerivation, assertRequirement, settleWithFakeTimers, and flushMicrotasks. For testing constraints, resolvers, derivations, effects, or time-travel behavior.
Ships in directive. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
This skill applies when the project uses @directive-run/core. If not found in package.json, suggest installing it: npm install @directive-run/core.
Auto-invoke when the user:
Do NOT invoke when:
writing-directive-modules.md)building-directive-systems.md)writing-directive-constraints.md)What are you testing?
├── A single module in isolation → createTestSystem(module)
├── Multiple modules together → createTestSystemFromModules({ a, b })
├── A constraint fires correctly → Set facts, call assertRequirement
├── A resolver mutates facts → Mock resolver, trigger, settle, assertFact
├── A derivation computes correctly → Set facts, call assertDerivation
├── Async/retry behavior → settleWithFakeTimers(system, vi)
├── Intermediate state (mid-resolve) → flushMicrotasks()
└── Time-travel / snapshots → Enable history in createTestSystem options
import {
createTestSystem,
createTestSystemFromModules,
mockResolver,
flushMicrotasks,
settleWithFakeTimers,
assertFact,
assertDerivation,
assertRequirement,
} from "@directive-run/core/testing";
// Minimal – testing defaults: time-travel off, no plugins, sync settling
const system = createTestSystem(myModule);
// With initial state
const system = createTestSystem(myModule, {
initialFacts: { count: 5, phase: "loading" },
});
// With mocked resolvers
const system = createTestSystem(myModule, {
mockResolvers: [
mockResolver("FETCH_USER", async (req, context) => {
context.facts.user = { id: req.userId, name: "Test User" };
}),
],
});
// Combined
const system = createTestSystem(myModule, {
initialFacts: { isAuthenticated: true, profile: null },
mockResolvers: [
mockResolver("FETCH_PROFILE", async (req, context) => {
context.facts.profile = { bio: "Test bio" };
}),
],
});
const system = createTestSystemFromModules(
{ auth: authModule, cart: cartModule },
{
mockResolvers: [
mockResolver("AUTHENTICATE", async (req, context) => {
// Resolvers write their own module's facts flat; other modules
// are read-only through context.deps.
context.facts.token = "test-token";
context.facts.isAuthenticated = true;
}),
],
},
);
Set facts to satisfy the constraint's when(), then assert the requirement was emitted.
describe("fetchWhenAuth constraint", () => {
it("emits FETCH_USER when authenticated without profile", () => {
const system = createTestSystem(userModule);
system.facts.isAuthenticated = true;
system.facts.profile = null;
assertRequirement(system, "FETCH_USER");
});
it("does NOT emit when profile already loaded", () => {
const system = createTestSystem(userModule, {
initialFacts: {
isAuthenticated: true,
profile: { id: "1", name: "Alice" },
},
});
const { requirements } = system.inspect();
const fetchReqs = requirements.filter((r) => r.type === "FETCH_USER");
expect(fetchReqs).toHaveLength(0);
});
it("emits dynamic requirement with correct payload", () => {
const system = createTestSystem(userModule, {
initialFacts: { isAuthenticated: true, userId: "u-42", profile: null },
});
// assertRequirement can check payload
assertRequirement(system, "FETCH_USER", { userId: "u-42" });
});
});
Mock the resolver, trigger the constraint, settle, then assert fact mutations.
describe("fetchUser resolver", () => {
it("stores fetched user and updates phase", async () => {
const system = createTestSystem(userModule, {
mockResolvers: [
mockResolver("FETCH_USER", async (req, context) => {
context.facts.user = { id: req.userId, name: "Mocked User" };
context.facts.phase = "loaded";
}),
],
});
system.facts.isAuthenticated = true;
system.facts.user = null;
await system.settle();
assertFact(system, "user", { id: expect.any(String), name: "Mocked User" });
assertFact(system, "phase", "loaded");
});
it("handles resolver error gracefully", async () => {
const system = createTestSystem(userModule, {
mockResolvers: [
mockResolver("FETCH_USER", async () => {
throw new Error("Network failure");
}),
],
});
system.facts.isAuthenticated = true;
system.facts.user = null;
// If error boundary uses "skip", settle resolves normally
await system.settle();
assertFact(system, "phase", "error");
});
});
Set facts, then read the derived value. No need to settle – derivations are synchronous.
describe("isOverBudget derivation", () => {
it("returns true when total exceeds budget", () => {
const system = createTestSystem(budgetModule, {
initialFacts: { total: 150, budget: 100 },
});
assertDerivation(system, "isOverBudget", true);
});
it("recomputes reactively when facts change", () => {
const system = createTestSystem(budgetModule, {
initialFacts: { total: 50, budget: 100 },
});
assertDerivation(system, "isOverBudget", false);
system.facts.total = 200;
assertDerivation(system, "isOverBudget", true);
});
});
Use settleWithFakeTimers when resolvers use retry delays, timeouts, or exponential backoff.
import { describe, it, expect, vi } from "vitest";
import { createTestSystem, settleWithFakeTimers, mockResolver, assertFact } from "@directive-run/core/testing";
describe("retry behavior", () => {
it("retries on failure with exponential backoff", async () => {
vi.useFakeTimers();
let attempts = 0;
const system = createTestSystem(myModule, {
mockResolvers: [
mockResolver("FETCH_DATA", async (req, context) => {
attempts += 1;
if (attempts < 3) {
throw new Error("Temporary failure");
}
context.facts.data = "success";
}),
],
});
system.facts.needsData = true;
// Advances fake timers through retry delays and waits for settlement
await settleWithFakeTimers(system, vi);
expect(attempts).toBe(3);
assertFact(system, "data", "success");
vi.useRealTimers();
});
});
Use flushMicrotasks() to process pending promises without fully settling.
it("shows loading phase during resolution", async () => {
const system = createTestSystem(myModule, {
mockResolvers: [
mockResolver("FETCH_DATA", async (req, context) => {
context.facts.phase = "loading";
await new Promise((resolve) => setTimeout(resolve, 100));
context.facts.phase = "done";
}),
],
});
system.facts.trigger = true;
await flushMicrotasks();
assertFact(system, "phase", "loading");
await system.settle();
assertFact(system, "phase", "done");
});
Effects run after reconciliation. Settle first, then check side effects.
describe("logPhase effect", () => {
it("logs when phase changes", async () => {
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
const system = createTestSystem(myModule, {
initialFacts: { phase: "idle" },
});
system.facts.phase = "loading";
await system.settle();
expect(consoleSpy).toHaveBeenCalledWith("Phase: loading");
consoleSpy.mockRestore();
});
});
Enable time-travel in the test system config. In most cases, prefer assertFact over snapshot testing.
describe("history", () => {
it("can undo a fact change", () => {
const system = createTestSystem(editorModule, {
history: { maxSnapshots: 20 },
});
system.facts.text = "Hello";
system.facts.text = "Hello, world";
const history = system.history;
expect(system.facts.text).toBe("Hello, world");
history.goBack();
expect(system.facts.text).toBe("Hello");
});
it("can export and import history", () => {
const system = createTestSystem(myModule, {
history: true,
});
system.facts.count = 1;
system.facts.count = 2;
const history = system.history;
const exported = history.export();
history.import(exported);
history.goTo(0);
expect(system.facts.count).toBe(1);
});
});
// WRONG – slow, flaky, external dependency
const system = createTestSystem(myModule);
system.facts.needsFetch = true;
await system.settle(); // Makes real HTTP call
// CORRECT – always mock resolvers in unit tests
const system = createTestSystem(myModule, {
mockResolvers: [mockResolver("FETCH", async (req, context) => {
context.facts.data = { mocked: true };
})],
});
// WRONG – resolver hasn't completed
system.facts.trigger = true;
assertFact(system, "result", "done"); // Fails
// CORRECT
system.facts.trigger = true;
await system.settle();
assertFact(system, "result", "done");
Always use (req, context) – never (req, ctx) or (request, context). Applies to mockResolver callbacks too.
// WRONG – testing internal resolver call count without behavior check
expect(mockFn).toHaveBeenCalledTimes(1);
// CORRECT – test the observable outcome (facts, derivations)
assertFact(system, "user", { id: "1", name: "Alice" });
assertDerivation(system, "isLoggedIn", true);
// WRONG – production system, no test defaults, runs plugins
const system = createSystem({ module: myModule });
// CORRECT – isolated, no plugins, testing utilities available
const system = createTestSystem(myModule);
// WRONG – leaks fake timers to other tests
vi.useFakeTimers();
await settleWithFakeTimers(system, vi);
// Missing vi.useRealTimers()
// CORRECT – always restore in afterEach or at the end of the test
vi.useFakeTimers();
await settleWithFakeTimers(system, vi);
vi.useRealTimers();
// Prefer assertFact/assertDerivation for most tests.
// Only enable time-travel when specifically testing undo/redo or snapshot export.
// CORRECT – use afterEach to clean up
let system: ReturnType<typeof createTestSystem>;
beforeEach(() => {
system = createTestSystem(myModule);
});
afterEach(() => {
system.destroy();
});
// Assert a fact value
assertFact(system, "phase", "done");
assertFact(system, "user", { id: expect.any(String) });
// Assert a derivation value
assertDerivation(system, "isLoading", false);
assertDerivation(system, "itemCount", 3);
// Assert a requirement was emitted
assertRequirement(system, "FETCH_USER");
assertRequirement(system, "FETCH_USER", { userId: "u-42" }); // With payload
// Inspect raw state
const { facts, requirements, resolvers, inflight } = system.inspect();
testing.md – full testing API, createTestSystem options, multi-module test setuphistory.md – history API, changesets, export/import, performance considerationsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
directive-testing, test-system, mock-resolver, assertions, fake-timers
Other plugins' skills for the same job
npx claudepluginhub directive-run/directive --plugin directive12 skills in this plugin
/building-ai-agentsConfigure AI provider runners (Anthropic, OpenAI, Ollama), stream tokens and structured output, and wire cross-agent communication. Use when setting up LLM provider connections, implementing token streaming, choosing between providers, or building agents that communicate results to each other./building-ai-orchestratorsCreate AI orchestration systems using createAgentOrchestrator (single agent) and createMultiAgentOrchestrator (multi-agent). Define factsSchema with t.*() builders, init state, constraints for trigger conditions, and resolvers for LLM execution. Use when building LLM-powered workflows, agent pipelines, task runners, or multi-agent coordination systems./building-directive-systemsCompose Directive modules into systems: single-module and multi-module createSystem() calls, namespaced fact/derive/event access, cross-module dependencies, initialFacts and hydration, plugins (logging, devtools, persistence, circuit breaker), React adapter hooks (useSelector, useEvent, useSystem, DirectiveProvider), and system lifecycle. Use when creating a system, connecting modules together, adding plugins, or integrating Directive with React./getting-started-with-directiveUnderstand Directive fundamentals: what modules, facts, derivations, constraints, resolvers, and systems are, and how they fit together. Use when someone is new to Directive, asks 'what is Directive', wants to understand the mental model, or needs help choosing between Directive concepts./hardening-ai-systemsAdd guardrails (input/output validation), memory strategies, token budgets, PII detection, prompt injection prevention, and circuit breakers to AI orchestrators. Use when enforcing content policies, managing costs, preventing security vulnerabilities, adding resilience, or implementing agent memory across turns./migrating-to-directiveMigrate state management code from Redux, Zustand, XState, MobX, Recoil, or Jotai to Directive. Provides concept mapping, step-by-step migration patterns, and before/after code examples. Use when asked to migrate, convert, or port existing state management to Directive.