@othree.io/chisel-forge
v3.0.0
Published
Chisel Test Utils
Readme
@othree.io/chisel-forge
Integration testing utilities for the Chisel CQRS/Event Sourcing framework. Provides a fluent API to send commands against deployed AWS infrastructure and validate triggered events and aggregate state.
Install
npm install @othree.io/chisel-forgePeer Dependencies
@othree.io/awsome^4.0.0@othree.io/chisel^5.0.0@othree.io/optional^2.3.2vitest^3.2.4
Quick Start~
import { when } from '@othree.io/chisel-forge'
import { Empty } from '@othree.io/optional'
type PersonState = Readonly<{
name: string
lastName: string
}>
const configuration = {
boundedContext: 'Person',
commandHandlerArn: 'arn:aws:lambda:us-east-1:123456789:function:PersonCommandHandler',
eventsTable: 'PersonEvents',
topicArn: 'arn:aws:sns:us-east-1:123456789:PersonEventsTopic',
testName: 'CreatePerson',
subscriptionAwaitTime: 3000,
loadStateLambdaArn: Empty(),
}
it('should create a person', async () => {
await when<PersonState>(configuration)({
type: 'CreatePerson',
body: { name: 'Chuck', lastName: 'Norris' },
})
.expectState({ name: 'Chuck', lastName: 'Norris' })
.expectEvent({
contextId: expect.any(String),
type: 'PersonCreated',
body: { name: 'Chuck', lastName: 'Norris' },
})
.toPass()
}, 30000)Command Handler Modes
The when() function supports three command delivery modes, determined by the configuration type.
Synchronous Lambda
Invokes the command handler Lambda directly and receives the CommandResult in the response.
const configuration = {
boundedContext: 'Person',
commandHandlerArn: 'arn:aws:lambda:...:PersonCommandHandler',
eventsTable: 'PersonEvents',
topicArn: 'arn:aws:sns:...:PersonEventsTopic',
testName: 'CreatePerson',
subscriptionAwaitTime: 3000,
loadStateLambdaArn: Empty(),
}Async SQS
Sends the command to an SQS queue. The command handler processes it asynchronously.
const configuration = {
boundedContext: 'Person',
commandQueueUrl: 'https://sqs.us-east-1.amazonaws.com/.../PersonCommandQueue.fifo',
commandDLQUrl: 'https://sqs.us-east-1.amazonaws.com/.../PersonCommandDLQ.fifo',
eventsTable: 'PersonEvents',
topicArn: 'arn:aws:sns:...:PersonEventsTopic.fifo',
testName: 'CreatePerson',
subscriptionAwaitTime: 3000,
loadStateLambdaArn: Empty(),
extractMessageGroupId: (command) => command.contextId,
extractMessageDeduplicationId: (command) => `${command.type}-${command.contextId}`,
}Async SNS
Sends the command to an SNS topic. The command handler subscribes and processes it asynchronously.
const configuration = {
boundedContext: 'Person',
commandTopicArn: 'arn:aws:sns:...:PersonCommandTopic.fifo',
commandDLQUrl: 'https://sqs.us-east-1.amazonaws.com/.../PersonCommandDLQ.fifo',
eventsTable: 'PersonEvents',
topicArn: 'arn:aws:sns:...:PersonEventsTopic.fifo',
testName: 'CreatePerson',
subscriptionAwaitTime: 3000,
loadStateLambdaArn: Empty(),
extractMessageGroupId: (command) => command.contextId,
extractMessageDeduplicationId: (command) => `${command.type}-${command.contextId}`,
}Fluent API
when<State>(configuration)(command)
Entry point. Accepts a configuration and returns a function that takes a Command and returns a test builder.
.and(getCommand)
Chains a subsequent command. The getCommand callback receives the contextId from the first command's result as an Optional<string>.
await when<PersonState>(configuration)({
type: 'CreatePerson',
body: { name: 'Chuck', lastName: 'Norris' },
})
.and((contextId) => ({
contextId: contextId.get(),
type: 'UpdatePerson',
body: { name: 'Bruce', lastName: 'Lee' },
}))
.expectState({ name: 'Bruce', lastName: 'Lee' })
.toPass().expectEvent(event)
Asserts that a specific ChiselEvent was triggered. Can be called multiple times for multiple expected events.
.expectEvent({
contextId: expect.any(String),
type: 'PersonCreated',
body: { name: 'Chuck', lastName: 'Norris' },
}).expectState(state)
Asserts the final aggregate state matches the expected value. When loadStateLambdaArn is configured, also validates the state returned by the load-state Lambda.
.toPass()
Executes the command(s), validates events and state, and returns the CommandResult array. Automatically cleans up temporary SQS queues, subscriptions, and events.
.toFail(errorMsg?)
Asserts the command fails with a CommandExecutionError. Optionally validates the error message.
const error = await when<PersonState>(configuration)({
type: 'CreatePerson',
body: { name: '', lastName: '' },
}).toFail('Validation failed')
expect(error.name).toEqual('CommandExecutionError')AWS Credentials
Pass optional AWS credentials as the second argument to when():
import { fromSSO } from '@aws-sdk/credential-providers'
const credentials = fromSSO({ profile: 'my-profile' })
await when<PersonState>(configuration, credentials)({
type: 'CreatePerson',
body: { name: 'Chuck', lastName: 'Norris' },
}).toPass()Low-Level API
For advanced use cases, the low-level functions are available under the lowLevel namespace:
import { lowLevel } from '@othree.io/chisel-forge'
const {
when,
runAndValidate,
runAndValidateAsync,
cleanUp,
createQueueAndSubscribe,
receiveMessages,
} = lowLevelThese accept explicit dependency objects, making them fully testable in isolation.
How It Works
- Creates a temporary SQS queue and subscribes it to the bounded context's SNS events topic
- Sends the command(s) to the command handler (Lambda, SQS, or SNS depending on config)
- Receives triggered event messages from the temporary queue
- Validates events and state against expectations
- Cleans up: deletes the temporary queue, unsubscribes from the topic, and removes events from the events table
Configuration Reference
| Property | Type | Required | Description |
|---|---|---|---|
| boundedContext | string | All | Bounded context name (matched against event message attributes) |
| topicArn | string | All | SNS topic ARN where the bounded context publishes events |
| eventsTable | string | All | DynamoDB events table name (for cleanup) |
| subscriptionAwaitTime | number | All | Milliseconds to wait after subscribing before sending commands |
| testName | string | All | Used to name the temporary SQS queue |
| loadStateLambdaArn | Optional<string> | All | Lambda ARN for loading aggregate state (optional validation) |
| commandHandlerArn | string | Sync | Lambda ARN for the command handler |
| commandQueueUrl | string | Async SQS | SQS queue URL for commands |
| commandTopicArn | string | Async SNS | SNS topic ARN for commands |
| commandDLQUrl | string | Async | SQS DLQ URL for failed commands |
| extractMessageGroupId | (command) => string | Async | FIFO message group ID extractor (optional) |
| extractMessageDeduplicationId | (command) => string | Async | FIFO deduplication ID extractor (optional) |
Scripts
npm test # Run tests
npm run build # Compile TypeScript
npm run docs # Generate JSDoc documentation