@bernierllc/email-testing-suite
v0.1.3
Published
Complete email testing solution with opinionated defaults, pre-configured test patterns, integrated mock server, and comprehensive reporting
Readme
@bernierllc/email-testing-suite
Complete email testing solution with opinionated defaults and best practices.
Features
- One-Command Setup - Start testing emails with minimal configuration
- Opinionated Defaults - Pre-configured validations and best practices
- Comprehensive Validation - Template, compliance, accessibility, performance, and security checks
- Advanced Analytics - Track trends, identify issues, generate reports
- Best Practices Enforcement - Automatic validation against email standards
- Integration Ready - Works with Jest, Mocha, Vitest, and other test frameworks
Installation
npm install @bernierllc/email-testing-suiteQuick Start
One-Line Testing
The simplest way to test an email:
import { testEmail } from '@bernierllc/email-testing-suite';
const result = await testEmail({
template: './templates/welcome.html',
data: { name: 'John Doe', product: 'Pro Plan' },
recipient: '[email protected]'
});
expect(result.success).toBe(true);
expect(result.score).toBeGreaterThan(90);Full Suite Usage
For more control and advanced features:
import { EmailTestingSuite } from '@bernierllc/email-testing-suite';
const suite = new EmailTestingSuite({
smtp: { port: 2525 },
defaults: { compliance: 'US', timeout: 30000 }
});
await suite.start();
const result = await suite.testEmailTemplate({
name: 'Welcome Email',
template: './templates/welcome.html',
data: { name: 'Jane Doe' },
recipients: ['[email protected]'],
expectations: {
delivery: true,
templateCompletion: true,
compliance: 'US',
accessibility: true,
performance: { renderTime: 2000, size: '100kb' }
}
});
await suite.stop();Configuration
Suite Configuration
interface EmailTestingSuiteConfig {
smtp?: {
port: number; // Default: 2525
host: string; // Default: 'localhost'
auth?: { user: string; pass: string; };
};
defaults?: {
compliance: 'US' | 'EU' | 'GLOBAL'; // Default: 'US'
timeout: number; // Default: 30000
retries: number; // Default: 3
expectations?: Partial<EmailExpectations>;
};
validation?: {
enabledValidators?: ValidatorType[]; // All enabled by default
strictMode?: boolean; // Default: false
customRules?: ValidationRule[]; // Custom validation rules
};
reporting?: {
enableAnalytics?: boolean; // Default: true
generateTrendReports?: boolean; // Default: true
exportFormats?: ReportFormat[]; // Default: ['json', 'html']
retainHistory?: number; // Days, default: 30
};
}Expectations
interface EmailExpectations {
delivery: boolean; // Email should be delivered
templateCompletion: boolean; // All variables resolved
compliance: 'US' | 'EU' | 'GLOBAL'; // Compliance standard
accessibility: boolean; // Accessibility validation
performance: {
renderTime?: number; // Max render time (ms)
size?: string; // Max email size (e.g., '100kb')
deliveryTime?: number; // Max delivery time (ms)
};
}Test Patterns
Pre-configured test patterns for common scenarios:
Welcome Email
import { EmailTestPatterns } from '@bernierllc/email-testing-suite';
const result = await EmailTestPatterns.testWelcomeEmail(
'./templates/welcome.html',
{ name: 'John Doe', email: '[email protected]' }
);Password Reset Email
const result = await EmailTestPatterns.testPasswordResetEmail(
'./templates/reset.html',
{ email: '[email protected]', resetLink: 'https://example.com/reset?token=abc' }
);Newsletter Email
const result = await EmailTestPatterns.testNewsletterEmail(
'./templates/newsletter.html',
{ title: 'Monthly Update', articles: [...] },
'[email protected]'
);Transactional Email
const result = await EmailTestPatterns.testTransactionalEmail(
'./templates/order-confirmation.html',
{ orderNumber: '12345', total: '$99.99' },
'[email protected]'
);Email Flow Testing
Test multi-step email workflows:
const flowResult = await suite.testEmailFlow({
name: 'User Onboarding Flow',
steps: [
{ trigger: 'user.signup', template: 'welcome', delay: 0 },
{ trigger: 'user.verify', template: 'verification', delay: 300000 },
{ trigger: 'user.complete', template: 'onboarding', delay: 86400000 }
],
assertions: [
{ step: 1, assertion: 'delivered' },
{ step: 2, assertion: 'contains_verification_link' },
{ step: 3, assertion: 'personalized_content' }
]
});Analytics
Track and analyze email testing performance:
import { EmailTestAnalytics } from '@bernierllc/email-testing-suite';
const analytics = new EmailTestAnalytics();
// Add test results
analytics.addTestResult(result);
// Generate analytics
const data = analytics.generateAnalytics('last_30_days');
console.log(`Success Rate: ${data.successRate}%`);
console.log(`Average Score: ${data.performanceMetrics.averageRenderTime}ms`);
// Export analytics
const json = analytics.exportAsJSON();
const csv = analytics.exportAsCSV();Best Practices
Get best practice recommendations:
import { BestPracticesValidator } from '@bernierllc/email-testing-suite';
// Validate email
const validation = BestPracticesValidator.validateEmail(emailData);
console.log(`Score: ${validation.score}`);
console.log(`Recommendations: ${validation.recommendations.length}`);
// Get compliance checklist
const checklist = BestPracticesValidator.getComplianceChecklist('US');
// Get accessibility guidelines
const guidelines = BestPracticesValidator.getAccessibilityGuidelines();
// Get performance tips
const tips = BestPracticesValidator.getPerformanceOptimizationTips();
// Get recommended coverage
const coverage = BestPracticesValidator.getRecommendedCoverage('marketing');Test Suite Execution
Run multiple tests together:
const tests = [
{
name: 'Welcome Email',
template: 'welcome.html',
data: { name: 'User 1' },
recipients: ['[email protected]']
},
{
name: 'Newsletter',
template: 'newsletter.html',
data: { content: '...' },
recipients: ['[email protected]']
}
];
const suiteResult = await suite.runTestSuite(tests);
console.log(`Total: ${suiteResult.totalTests}`);
console.log(`Passed: ${suiteResult.passedTests}`);
console.log(`Failed: ${suiteResult.failedTests}`);
console.log(`Average Score: ${suiteResult.summary.averageScore}`);Jest Integration
describe('Email Templates', () => {
let suite: EmailTestingSuite;
beforeAll(async () => {
suite = new EmailTestingSuite({
smtp: { port: process.env.SMTP_PORT || 2525 },
defaults: { compliance: 'US', timeout: 30000 }
});
await suite.start();
});
afterAll(async () => {
await suite.stop();
});
test('welcome email passes validation', async () => {
const result = await suite.testEmailTemplate({
name: 'Welcome Email',
template: './templates/welcome.html',
data: { name: 'Test User' },
recipients: ['[email protected]']
});
expect(result.success).toBe(true);
expect(result.score).toBeGreaterThan(90);
});
});Data Generation
Generate test data from a schema:
const schema = {
name: { type: 'string', required: true },
email: { type: 'email', required: true },
age: { type: 'number', min: 18, max: 100 },
joinDate: { type: 'date' },
website: { type: 'url' },
userId: { type: 'uuid' }
};
const testData = suite.generateTestData(schema);
// Returns: { name: 'test-name', email: '[email protected]', age: 18, ... }API Reference
EmailTestingSuite
constructor(config?: EmailTestingSuiteConfig)- Create new suite instanceasync start()- Start the testing environmentasync stop()- Stop the testing environmentasync reset()- Reset captured emails and stateasync testEmailTemplate(spec: EmailTemplateTest)- Test an email templateasync testEmailFlow(flow: EmailFlowTest)- Test an email flowasync runTestSuite(tests: EmailTest[])- Run multiple testsgetTestingEnvironment()- Get current environment stategenerateTestData(schema: DataSchema)- Generate test datagetTestHistory()- Get all test resultsclearTestHistory()- Clear test history
EmailTestAnalytics
addTestResult(result: EmailTestResult)- Add single resultaddTestResults(results: EmailTestResult[])- Add multiple resultsgenerateAnalytics(period: string)- Generate analytics reportexportAsJSON(period?: string)- Export as JSONexportAsCSV(period?: string)- Export as CSVgetTestHistory()- Get all resultsclearHistory()- Clear history
BestPracticesValidator
static validateEmail(email: EmailData)- Validate email against best practicesstatic getRecommendedCoverage(emailType: string)- Get recommended validatorsstatic getComplianceChecklist(region: 'US' | 'EU' | 'GLOBAL')- Get compliance checkliststatic getAccessibilityGuidelines()- Get accessibility guidelinesstatic getPerformanceOptimizationTips()- Get performance tips
License
Copyright (c) 2025 Bernier LLC
This file is licensed to the client under a limited-use license.
