/bett3r-pv3-ai-skills:create-testsfrom bett3r-pv3-ai-skills
Generate tests using Given/When/Then pattern for PV3 DDD components. Use when adding tests for aggregates, policies, and readmodels.
Ships in bett3r-pv3-ai-skills. 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.
None: SKILL.md is the whole skill.
Generate co-located test files for PV3 DDD components using Jest and Given/When/Then structure.
Open the ddd-patterns reference for the artifact you are testing — each one names the fixtures that are required, not optional, and they are the cases a happy-path suite silently omits: AGGREGATES.md (the happy-path + state-rejection pair per status-guarded command; the STATE_NOT_FOUND test for every state-reading idempotency predicate; the lock acquire/release fixtures), POLICIES.md (the redelivery-after-partial-progress test asserting zero duplicate events), READMODELS.md (the interleaved brand-new-key concurrency test), and DELIVERY.md for what redelivery a test has to simulate. ddd-patterns → SKILL.md has the trigger table.
When the scaffold already wrote test files, their it.todo cases sit behind a TODO(scaffold) marker; skip generating those files. Keep each case's title, and a scenario case's
<scenarioId>: prefix above all: the verifier's pending-test check keys on that prefix and the scaffold matches it to tell a test already landed, so rewording a title while turning it.todo into it breaks both silently. Work only the TODO(scaffold) markers (every scaffolded case carries one) and
the STILL OWED block where there is one (a file holding integration cases), and delete each marker as you satisfy it. Turn each it.todo into a real Given/When/Then case, and add the required fixtures the reference lists. The rest of this
skill still governs the content you write and the Final Checklist.
Resolve these placeholders from .blueprint.config.json at the repo root:
| Placeholder | .blueprint.config.json field | Example value |
|---|---|---|
<serverPath> | serverPath | src/services/server |
The framework packages @bett3r-dev/pv3-types, @bett3r-dev/jsonschema-definer, and the
ports module are PV3 framework — identical in every PV3 repo — and appear verbatim below.
Default here, not E2E. Per the host repo's testing rules § "Test Level": anything
assertable by calling a command/endpoint and reading the event store or readmodel
belongs at this (in-process) level. Happy paths are covered by integration
tests, not E2E. Reserve Playwright (e2e-create-tests) for browser-specific risk
only (rendering, route guards, input devices, navigation) — one smoke per journey.
Two in-process shapes this skill produces:
await createTestPorts() + testCommandHandler() /
testPolicy() / testReadmodel() (mock infrastructure).*.integration.test.ts and put it in an integration suite under the host
repo's integration-tests package (see the create-integration-test skill): boot
the full in-memory pipeline via createIntegrationHarness({ modules, testUser }),
drive it with the typed client library / endpoints.fetch, assert the event store
yarn test:integration (NOT yarn test,
which excludes integration tests). Put a test under a channel path only if it hits
a real external service — those run via yarn test:integration:channels.Tests are co-located next to their source file:
<serverPath>/src/modules/<module-name>/
orders.aggregate.ts
orders.aggregate.test.ts # <-- test file
orders.readmodel.ts
orders.readmodel.test.ts # <-- test file
myProcess.policy.ts
myProcess.policy.test.ts # <-- test file
Co-location is the default shown here and holds only where the host declares it
(designTooling.tests in .blueprint.config.json); a host that declares a directory placement
puts tests there instead, so follow the host's declaration.
describe( 'MyComponent', () => {
// Setup
let ports: any;
beforeEach( async () => {
ports = await createTestPorts();
jest.clearAllMocks();
});
// ═══════════════════════════════════════════════
// GIVEN: [precondition description]
// ═══════════════════════════════════════════════
describe( 'Given [precondition]', () => {
it( 'when [action] then [expected result]', async () => {
// GIVEN
const setupData = { ... };
// WHEN
const result = await executeAction( setupData );
// THEN
expect( result ).toMatchObject({ ... });
});
});
});
import { createTestPorts } from '@bett3r-dev/pv3-library-tests';
import { MyAggregate } from './my.aggregate';
describe( 'MyAggregate', () => {
let ports: any;
let aggregate: ReturnType<typeof MyAggregate>;
beforeEach( async () => {
ports = await createTestPorts();
aggregate = MyAggregate( ports );
});
// ═══════════════════════════════════════════════
// GIVEN: No existing entity
// ═══════════════════════════════════════════════
describe( 'Given no existing entity', () => {
it( 'when CreateEntity command then EntityCreated event emitted', async () => {
// Test command handler logic
// Verify events are created with correct data
});
});
// ═══════════════════════════════════════════════
// GIVEN: Existing entity
// ═══════════════════════════════════════════════
describe( 'Given existing entity', () => {
it( 'when EditEntity command then EntityEdited event emitted with diff', async () => {
// Test that only changed fields are in the event
});
it( 'when ChangeStatus command then EntityStatusChanged event emitted', async () => {
// Test status change includes previousStatus
});
});
});
import { createTestPorts } from '@bett3r-dev/pv3-library-tests';
import { testPolicy } from '@bett3r-dev/pv3-library-tests';
import { MyPolicy } from './my.policy';
describe( 'MyPolicy', () => {
let ports: any;
let mockClientLibrary: any;
beforeEach( async () => {
ports = await createTestPorts();
mockClientLibrary = {
commands: {
DoSomething: jest.fn().mockResolvedValue( undefined )
},
queries: {
GetSomething: jest.fn().mockResolvedValue( mockData )
}
};
});
it( 'Given SomethingHappened event when policy processes then triggers downstream command', async () => {
// GIVEN
const event = {
id: 'event-id',
data: { entityId: 'entity-1', value: 42 },
metadata: {
accountId: 'account-1',
correlationId: 'corr-1',
userId: 'user-1'
},
stream: 'MyAggregate-entity-1'
};
// WHEN
const policy = MyPolicy( ports );
// Execute the policy handler directly
// THEN
expect( mockClientLibrary.commands.DoSomething ).toHaveBeenCalledWith(
expect.objectContaining({ entityId: 'entity-1' })
);
});
});
import { createTestPorts } from '@bett3r-dev/pv3-library-tests';
import { MyReadmodel } from './my.readmodel';
describe( 'MyReadmodel', () => {
let ports: any;
let mockCollection: any;
beforeEach( async () => {
mockCollection = {
upsert: jest.fn().mockResolvedValue( undefined ),
query: jest.fn().mockResolvedValue([]),
count: jest.fn().mockResolvedValue( 0 ),
ensureIndex: jest.fn().mockResolvedValue( undefined )
};
ports = await createTestPorts();
ports.database.getCollection = jest.fn().mockReturnValue( mockCollection );
});
// ═══════════════════════════════════════════════
// Projector Tests
// ═══════════════════════════════════════════════
describe( 'Projectors', () => {
it( 'Given EntityCreated event then upserts with full data + accountId + ownerId', async () => {
const event = {
data: { name: 'Test', status: 'active' },
metadata: { accountId: 'account-1', userId: 'user-1' },
stream: 'MyEntity-entity-1'
};
// Execute projector
// ...
expect( mockCollection.upsert ).toHaveBeenCalledWith( 'entity-1', {
name: 'Test',
status: 'active',
accountId: 'account-1',
ownerId: 'user-1'
});
});
it( 'Given EntityEdited event then upserts with partial data', async () => {
// Test partial update
});
});
// ═══════════════════════════════════════════════
// Query Tests
// ═══════════════════════════════════════════════
describe( 'Queries', () => {
it( 'Given authenticated user when search then returns filtered results', async () => {
// Test query handler with user context
});
it( 'Given no user when query then throws UnauthorizedError', async () => {
// Test authentication requirement
});
});
});
const createEvent = ( type: string, data: any, overrides: any = {} ) => ({
id: `event-${Date.now()}`,
type,
data,
stream: `MyEntity-${overrides.entityId || 'test-entity-1'}`,
metadata: {
accountId: overrides.accountId || 'test-account-1',
correlationId: overrides.correlationId || 'test-correlation-1',
userId: overrides.userId || 'test-user-1',
...overrides.metadata
},
...overrides
});
const createMockPorts = () => ({
logger: {
createLoggerInstance: () => ({
log: jest.fn(),
error: jest.fn(),
warn: jest.fn()
})
},
database: {
getCollection: jest.fn(),
onStarted: jest.fn()
},
eventsourcing: {
routeCommandHandler: jest.fn(),
routeEventHandler: jest.fn(),
PolicyBuilder: jest.fn()
},
endpoints: {
fetch: jest.fn()
}
});
yarn test # All tests
npx jest <path> --verbose # Specific file
yarn test -- --watchAll # Watch mode
Tests that execute commands (directly or via policy handlers) need an execution context to simulate the HTTP middleware context that exists at runtime. Wrap command execution in runWithExecutionContext:
import { runWithExecutionContext } from '@bett3r-dev/pv3';
// Wrap the command or policy handler call
await runWithExecutionContext(
{ accountId: 'test-account', userId: 'test-user', correlationId: 'test-corr' },
async () => {
// Execute command or policy handler here
await ports.eventsourcing.executeCommand( MyAggregate( ports ), 'DoSomething' )({
params: { id: 'entity-1' },
body: { name: 'Test' }
});
}
);
When to use: Any test that calls executeCommand or triggers a policy handler that calls executeCommand internally. The context provides accountId, userId, correlationId, and optionally causationId — the same values that the ALS middleware and PolicyBuilder set automatically at runtime.
Note: For policy tests, if you invoke the policy handler directly with an event that has metadata.accountId and metadata.userId, the PV3 PolicyBuilder wrapper automatically sets up the execution context from the event metadata. You only need manual runWithExecutionContext when calling executeCommand outside of a PolicyBuilder-wrapped handler.
.rejects.toBeDefined() or .rejects.toThrow() without a code check is not acceptable when the test title or spec names a specific error code. Use expect(promise).rejects.toMatchObject({ code: 'ERROR_CODE' }) or the project's expectRejectsWithCode helper. This applies to both hand-thrown BadRequestErrors AND framework invariants — e.g. invariants.stateExists() rejects with { code: 'STATE_NOT_EXISTS' } and must be asserted the same way.*.test.ts next to source file, unless the host declares otherwise (designTooling.tests)await createTestPorts() (it is async) — From @bett3r-dev/pv3-library-tests when available═══ comment separators for readability*.integration.test.ts filenames in the co-located unit suite — that suffix may be excluded by the unit jest.config.js; cross-aggregate integration suites must use a different suffix (e.g. *.flows.test.ts) or live in the host repo's integration-tests packageexpect(calls).toHaveLength(0) is only meaningful after the policy fires; assert after testPolicy(...).when(...).then(...), not beforeaccountId in the body and asserting it in event.data passes against a handler that merely spreads the body. Omit it from the body, inject it via context.user, then assert it still arrives. testCommandHandler builds context.user as { id } only and cannot express an authenticated caller's accountId — that oracle needs a thin wrapper around ports.eventsourcing.executeCommand.MemoryDb does not enforce PRIMARY KEY — createMany assigns coll[id] directly; only validateIndex rejects. A claim table whose uniqueness guard is a derived-id PK (the customers precedent) has that guard unexercised in the memory harness: the duplicate is caught by the secondary unique index, so the test passes for the wrong reason and stays green with the real guard removed. A storage-enforced constraint is proven on createPostgresIntegrationHarness or not at all; the memory harness is for choreography and projection shape.| Component | Test Focus |
|---|---|
| Aggregate | Command handlers: correct events emitted, state transitions, edge cases |
| Policy | Event handlers: correct side effects, error handling, idempotency |
| Readmodel | Projectors: correct upserts; Queries: auth, filtering, pagination |
<component>.test.tsdescribe blocks group by precondition═══ separators between test groupsbeforeEachnpx jest <path> --verboseWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub bett3r-dev/bett3r-ai-workflow --plugin bett3r-pv3-ai-skills11 skills in this plugin
/create-aggregateSkill: Create AggregateScaffold a new event-sourced aggregate with PV3 AggregateBuilder pattern. Use when adding a new aggregate to handle commands and emit events./create-integration-testSkill: Create Integration TestScaffold a full-pipeline in-process integration test suite for a server module using createIntegrationHarness. Use when you want to exercise the real command → aggregate → eventstore → outbox → readmodel pipeline for a subdomain (choreography, policies, gateway callbacks), not mocked unit tests./create-Other plugins' skills for the same job