@bernierllc/email-test-orchestrator
v0.8.1
Published
Service package that orchestrates comprehensive email testing workflows
Readme
@bernierllc/email-test-orchestrator
Service package that runs email tests end to end: it starts a real mock SMTP server, sends the email under test over SMTP, captures what arrived, runs validators against the captured message and produces a scored report.
Installation
npm install @bernierllc/email-test-orchestratorFeatures
- Real SMTP round trip - emails are sent with
@bernierllc/email-senderto a@bernierllc/mock-smtp-serverinstance and validated as received, raw source included - Template rendering -
{{variable}}subjects and bodies rendered with@bernierllc/template-engine - Built-in validators - delivery, content, template and compliance (
@bernierllc/email-validator), weighted into one score - Custom validators - plug your own validator in for any validator type with
registerValidator() - Capture by Message-ID - every send is matched to its own captured email by Message-ID, so repeated subjects and concurrent tests never pick up each other's mail
- Decoded content - quoted-printable, base64 and encoded-word subjects and bodies arrive decoded (
Café 🎉, notCaf=C3=A9) - Typed errors - every failure is an
EmailTestOrchestratorErrorwith a code and the underlying cause - NeverHub registration - optional service discovery
Usage
Basic example
import { EmailTestOrchestrator } from '@bernierllc/email-test-orchestrator';
const orchestrator = new EmailTestOrchestrator();
// Starts the mock SMTP server on an OS-assigned port (127.0.0.1)
const context = await orchestrator.setupTestEnvironment({ session: { name: 'welcome' } });
try {
const result = await orchestrator.runEmailTest({
name: 'Welcome email',
description: 'Renders the template and lands in the inbox',
sender: { email: '[email protected]' },
recipients: [{ email: '[email protected]', name: 'Ada' }],
template: { name: 'welcome', subject: 'Welcome {{name}}', body: 'Hello {{name}}, thanks for joining.' },
data: { name: 'Ada' },
expectations: [
{ type: 'delivery', criteria: { to: '[email protected]' }, weight: 2 },
{ type: 'content', criteria: { subject: 'Welcome Ada', contains: 'thanks' } },
{ type: 'template', criteria: { variables: ['Ada'] } },
{ type: 'compliance', criteria: {} },
],
});
console.log(`Test ${result.success ? 'passed' : 'failed'} with score ${result.score}`);
for (const issue of result.issues) console.log(issue.severity, issue.type, issue.message);
} finally {
await context.cleanup();
}A test without a template has no body to send and fails with SEND_FAILED; give every spec a template.
Test environment
setupTestEnvironment() must run before anything that sends. It starts one mock SMTP server per orchestrator:
const context = await orchestrator.setupTestEnvironment({
mockServer: { port: 0, host: '127.0.0.1' }, // both are the defaults; port 0 = OS-assigned
session: { name: 'integration-test' },
});
console.log(context.sessionId, context.mockServerPort);
await orchestrator.cleanupTestEnvironment(context.sessionId); // same as context.cleanup()- Calling it twice without cleanup, or again while the first call is still starting, throws
INVALID_INPUT. - If the server cannot start (for example, the fixed port is taken), it throws
OPERATION_FAILED. - Cleanup is idempotent. It ignores unknown session ids and still succeeds when the server is already down.
Send and capture
const email = await orchestrator.sendAndCapture({
from: { email: '[email protected]', name: 'Sender' },
to: [{ email: '[email protected]' }],
subject: 'Hello {{name}}',
text: 'Plain body', // or html, or template (template supplies the body)
data: { name: 'Bob' },
});
console.log(email.subject, email.body, email.raw?.length);It returns the email whose Message-ID matches the one sent, even when earlier emails share the subject. The subject always comes from options.subject, rendered with data. A template supplies only the body: type: 'html' sends HTML, and anything else sends text.
Execute a test suite
const suite = await orchestrator.executeTestSuite([welcomeSpec, resetSpec]);
console.log(suite.success, `${suite.report.summary.passed}/${suite.report.summary.totalTests} passed`);Tests run in order. runEmailTest() calls can also run concurrently against one environment; each test captures only its own emails. A failing test is recorded as a failed result, and the remaining tests still run.
Validate a captured email
const results = await orchestrator.validateEmail(email, [
{ type: 'content', criteria: { hasSubject: true, hasBody: true } },
{ type: 'compliance', criteria: {} },
]);
for (const r of results) console.log(r.type, r.success, r.score, r.errors);Wait for delivery
const found = await orchestrator.waitForDelivery(email.id, 5000); // CapturedEmail | nullGenerate a report
const report = await orchestrator.generateReport([result1, result2]);
console.log(report.summary); // { totalTests, passed, failed, score, duration }An empty result list scores 0.
Validators
Each expectation names a validator type. The test score is the weighted average of the validator scores (weight defaults to 1). Validator types not in validation.enabledValidators are skipped.
| Type | Criteria |
|------|----------|
| delivery | to: the address, or addresses, that must be among the recipients. from: the exact sender address. Being captured is itself the proof of delivery. |
| content | hasSubject, hasBody (booleans). subject: exact match. contains, notContains: a string or a list of strings, checked against the body and HTML. |
| template | Fails if template syntax is left unrendered, found by @bernierllc/template-validator: {{ }} (including block helpers and filters), {% %} and <%= %>. Each leftover becomes an error such as Unrendered template syntax "{{ name }}" at line 2. variables: rendered values (a string or a list) that must appear in the subject, body or HTML. |
| compliance | Runs @bernierllc/email-validator on the raw source; criteria are its EmailValidationOptions. It fails when no raw source was captured. |
| smtp | Same as compliance, until you register your own validator. |
Custom validators
orchestrator.registerValidator('smtp', {
validate: (email, criteria) => ({
success: email.headers['x-mailer'] === criteria.mailer,
errors: email.headers['x-mailer'] === criteria.mailer ? [] : ['unexpected mailer'],
}),
});registerValidator() replaces the validator for that type. score defaults to 100 on success and 0 on failure. A validator that throws becomes a failed result carrying the error message, and the rest of the validators still run. With validation.parallelValidation: false, validators run in order.
Configuration
interface OrchestratorConfig {
validation?: {
enabledValidators?: ValidatorType[]; // default: all five
parallelValidation?: boolean; // default: true
validationTimeout?: number; // accepted, not yet used
};
capture?: { sessionTimeout?: number; retentionPolicy?: string }; // accepted, not yet used
reporting?: { formats?: ReportFormat[]; includeRawEmails?: boolean; includeScreenshots?: boolean }; // accepted, not yet used
logger?: Logger; // { info?, error?, ... }; default: console
/** @deprecated since 0.8.0; removed in 1.0.0; use setupTestEnvironment({ mockServer: { port, host } }) */
smtp?: { host?: string; port?: number; secure?: boolean; auth?: { user: string; pass: string } };
}Deprecation: smtp
smtp is deprecated since 0.8.0 and will be removed in 1.0.0. It is ignored, and the first orchestrator constructed with it logs a one-time console.warn: emails always go to the mock SMTP server started by setupTestEnvironment(), because that server is where they are captured. To migrate, delete the smtp block and use setupTestEnvironment({ mockServer: { port, host } }) if you need a fixed address.
Error Handling
Every failure throws an EmailTestOrchestratorError with a code, an optional context, and the underlying error as cause (ES2022 Error.cause):
| Code | When |
|------|------|
| NOT_INITIALIZED | Sending before setupTestEnvironment(), or after cleanup |
| INVALID_INPUT | setupTestEnvironment() called while an environment is active |
| OPERATION_FAILED | The mock SMTP server could not start |
| SEND_FAILED | The SMTP send failed. context holds the recipient and subject; cause is the original transport error. |
| CAPTURE_TIMEOUT | Sent emails (matched by Message-ID) did not arrive within the spec timeout |
| VALIDATOR_NOT_FOUND | An enabled validator type has no registered validator |
import { EmailTestOrchestratorError } from '@bernierllc/email-test-orchestrator';
try {
await orchestrator.sendAndCapture(options);
} catch (error) {
if (error instanceof EmailTestOrchestratorError && error.code === 'SEND_FAILED') {
console.error(error.message, error.context, error.cause);
}
throw error;
}runEmailTest() does not throw for a failed test. It returns success: false, and each problem appears as an entry in issues.
NeverHub
initialize() registers the package with NeverHub when NEVERHUB_API_URL (or NEVERHUB_ENDPOINT / NEVERHUB_HOST) is set. Without them it does nothing. Every other method works whether or not you call it.
await orchestrator.initialize();Dependencies
@bernierllc/mock-smtp-server- captures the sent emails@bernierllc/email-sender- sends over SMTP@bernierllc/template-engine- renders subjects and bodies@bernierllc/template-validator- finds unrendered template syntax@bernierllc/email-validator- compliance and SMTP validation of the raw source@bernierllc/neverhub-adapter- optional service discovery
Proof app
proof/email-test-orchestrator installs this package from packed tarballs. It exercises every public method over real SMTP: cd proof/email-test-orchestrator && npm run proof:run.
License
Copyright (c) 2025 Bernier LLC. This file is licensed to the client under a limited-use license.
