Initial push of Plunk Next

This commit is contained in:
Dries Augustyns
2025-12-01 09:56:56 +01:00
parent 07cea20262
commit ff1876d580
566 changed files with 89036 additions and 28423 deletions
+186
View File
@@ -0,0 +1,186 @@
import {PrismaClient} from '@plunk/db';
import {execSync} from 'child_process';
/**
* Test database helper
* Manages test database isolation and cleanup
*/
class TestDatabase {
private prisma: PrismaClient | null = null;
async initialize() {
// Use test database URL if provided, otherwise use main database
const databaseUrl = process.env.TEST_DATABASE_URL || process.env.DATABASE_URL;
if (!databaseUrl) {
throw new Error('DATABASE_URL or TEST_DATABASE_URL must be set for testing');
}
// Create Prisma client with connection pool limits
this.prisma = new PrismaClient({
datasources: {
db: {
url: databaseUrl,
},
},
// Limit connection pool to prevent memory issues in tests
// @ts-ignore - These options exist but may not be in types
__internal: {
engine: {
connection_limit: 5,
},
},
});
// Connect to database
await this.prisma.$connect();
// Run migrations (only once per test suite)
try {
execSync('yarn workspace @plunk/db migrate:dev', {
env: {
...process.env,
DATABASE_URL: databaseUrl,
},
stdio: 'ignore',
});
} catch (error) {
console.warn('Migration warning (may already be up to date):', error);
}
}
/**
* Get Prisma client instance
*/
getClient(): PrismaClient {
if (!this.prisma) {
throw new Error('Database not initialized. Call initialize() first.');
}
return this.prisma;
}
/**
* Clean up database after each test
* Deletes all records in reverse order of dependencies
* Uses batched deletes to prevent memory issues with large datasets
*/
async cleanup() {
if (!this.prisma) return;
try {
// Use a transaction to ensure all deletes happen atomically
// This prevents foreign key constraint violations and race conditions
await this.prisma.$transaction([
// Level 1: Delete deepest dependencies first
this.prisma.event.deleteMany(),
this.prisma.workflowStepExecution.deleteMany(),
// Level 2: Delete entities that depend on Level 1
this.prisma.email.deleteMany(),
this.prisma.workflowExecution.deleteMany(),
// Level 3: Delete workflow structure
this.prisma.workflowTransition.deleteMany(),
this.prisma.workflowStep.deleteMany(),
this.prisma.workflow.deleteMany(),
// Level 4: Delete campaigns and templates
this.prisma.campaign.deleteMany(),
this.prisma.template.deleteMany(),
// Level 5: Delete segment relationships
this.prisma.segmentMembership.deleteMany(),
this.prisma.segment.deleteMany(),
// Level 6: Delete contacts
this.prisma.contact.deleteMany(),
// Level 7: Delete domains
this.prisma.domain.deleteMany(),
// Level 8: Delete memberships (has FK to both user and project)
this.prisma.membership.deleteMany(),
// Level 9: Delete projects
this.prisma.project.deleteMany(),
// Level 10: Delete users last
this.prisma.user.deleteMany(),
]);
} catch (error) {
console.error('Error cleaning up database:', error);
throw error;
}
}
/**
* Disconnect from database
*/
async disconnect() {
if (this.prisma) {
await this.prisma.$disconnect();
this.prisma = null;
}
}
/**
* Execute raw SQL (useful for advanced test setup)
*/
async executeRaw(sql: string) {
if (!this.prisma) {
throw new Error('Database not initialized');
}
return this.prisma.$executeRawUnsafe(sql);
}
/**
* Reset database sequences (useful for predictable IDs in tests)
*/
async resetSequences() {
if (!this.prisma) return;
// Get all tables with sequences
const tables = [
'User',
'Project',
'Contact',
'Campaign',
'Email',
'Workflow',
'WorkflowExecution',
'Template',
'Segment',
];
for (const table of tables) {
try {
await this.prisma.$executeRawUnsafe(`ALTER SEQUENCE "${table}_id_seq" RESTART WITH 1`);
} catch (error) {
// Sequence might not exist, ignore
}
}
}
}
// Export singleton instance
export const testDatabase = new TestDatabase();
// Export helper to get Prisma client in tests
// Returns a Proxy that lazily initializes the database on first property access
export const getPrismaClient = (() => {
let clientProxy: PrismaClient | null = null;
return () => {
if (!clientProxy) {
clientProxy = new Proxy({} as PrismaClient, {
get(target, prop) {
const client = testDatabase.getClient();
const value = client[prop as keyof PrismaClient];
// Bind methods to the actual client
return typeof value === 'function' ? value.bind(client) : value;
},
});
}
return clientProxy;
};
})();
+560
View File
@@ -0,0 +1,560 @@
import {
PrismaClient,
AuthMethod,
Role,
TemplateType,
CampaignStatus,
EmailStatus,
EmailSourceType,
WorkflowTriggerType,
WorkflowStepType,
WorkflowExecutionStatus,
StepExecutionStatus,
} from '@plunk/db';
import {getPrismaClient} from './database';
import bcrypt from 'bcrypt';
/**
* Factory helpers for creating test data
* These factories create database records with sensible defaults
*/
let factoryCounter = 0;
function uniqueId() {
return `${Date.now()}-${factoryCounter++}`;
}
export interface UserFactoryOptions {
email?: string;
password?: string;
type?: AuthMethod;
}
export interface ProjectFactoryOptions {
name?: string;
disabled?: boolean;
trackingEnabled?: boolean;
billingLimitWorkflows?: number | null;
billingLimitCampaigns?: number | null;
billingLimitTransactional?: number | null;
}
export interface ContactFactoryOptions {
projectId: string;
email?: string;
data?: Record<string, unknown>;
subscribed?: boolean;
}
export interface TemplateFactoryOptions {
projectId: string;
name?: string;
subject?: string;
body?: string;
from?: string;
fromName?: string;
type?: TemplateType;
}
export interface CampaignFactoryOptions {
projectId: string;
name?: string;
subject?: string;
body?: string;
from?: string;
status?: CampaignStatus;
scheduledFor?: Date | null;
segmentId?: string | null;
}
export interface WorkflowFactoryOptions {
projectId: string;
name?: string;
enabled?: boolean;
triggerType?: WorkflowTriggerType;
triggerConfig?: unknown;
allowReentry?: boolean;
}
export interface WorkflowStepFactoryOptions {
workflowId: string;
type?: WorkflowStepType;
name?: string;
position?: {x: number; y: number};
config?: unknown;
templateId?: string | null;
}
export class TestFactories {
private prisma: PrismaClient;
constructor() {
this.prisma = getPrismaClient();
}
/**
* Create a test user
*/
async createUser(options: UserFactoryOptions = {}) {
const email = options.email || `user-${uniqueId()}@test.com`;
const password = options.password || 'password123';
const hashedPassword = await bcrypt.hash(password, 10);
return this.prisma.user.create({
data: {
email,
password: hashedPassword,
type: options.type || AuthMethod.PASSWORD,
},
});
}
/**
* Create a test project
*/
async createProject(options: ProjectFactoryOptions = {}) {
return this.prisma.project.create({
data: {
name: options.name || `Test Project ${uniqueId()}`,
public: `pk_${uniqueId()}`,
secret: `sk_${uniqueId()}`,
disabled: options.disabled || false,
trackingEnabled: options.trackingEnabled ?? true,
billingLimitWorkflows: options.billingLimitWorkflows,
billingLimitCampaigns: options.billingLimitCampaigns,
billingLimitTransactional: options.billingLimitTransactional,
},
});
}
/**
* Create a user with a project
*/
async createUserWithProject(userOptions: UserFactoryOptions = {}, projectOptions: ProjectFactoryOptions = {}) {
const user = await this.createUser(userOptions);
const project = await this.createProject(projectOptions);
await this.prisma.membership.create({
data: {
userId: user.id,
projectId: project.id,
role: Role.ADMIN,
},
});
return {user, project};
}
/**
* Create a test contact
*/
async createContact(options: ContactFactoryOptions) {
return this.prisma.contact.create({
data: {
projectId: options.projectId,
email: options.email || `contact-${uniqueId()}@test.com`,
data: options.data || {},
subscribed: options.subscribed ?? true,
},
});
}
/**
* Create multiple contacts using bulk insert for better performance and memory efficiency
*/
async createContacts(projectId: string, count: number, baseOptions: Partial<ContactFactoryOptions> = {}) {
// Use createMany for bulk insert to avoid memory issues
const contactsData = Array.from({length: count}, (_, i) => ({
projectId,
email: `contact-${i}-${uniqueId()}@test.com`,
data: baseOptions.data || {},
subscribed: baseOptions.subscribed ?? true,
}));
await this.prisma.contact.createMany({
data: contactsData,
});
// Fetch the created contacts to return them (needed for test assertions)
// Use a limited query to avoid loading too many at once
return this.prisma.contact.findMany({
where: {projectId},
orderBy: {createdAt: 'desc'},
take: count,
});
}
/**
* Create a test template
*/
async createTemplate(options: TemplateFactoryOptions) {
return this.prisma.template.create({
data: {
projectId: options.projectId,
name: options.name || `Template ${uniqueId()}`,
subject: options.subject || 'Test Subject',
body: options.body || '<p>Hello {{firstName}}, this is a test email.</p>',
from: options.from || '[email protected]',
fromName: options.fromName || 'Test Sender',
type: options.type || TemplateType.MARKETING,
},
});
}
/**
* Create a test campaign
*/
async createCampaign(options: CampaignFactoryOptions) {
return this.prisma.campaign.create({
data: {
projectId: options.projectId,
name: options.name || `Campaign ${uniqueId()}`,
subject: options.subject || 'Test Campaign Subject',
body: options.body || '<p>Test campaign body</p>',
from: options.from || '[email protected]',
status: options.status || CampaignStatus.DRAFT,
scheduledFor: options.scheduledFor,
segmentId: options.segmentId,
},
});
}
/**
* Create a scheduled campaign
* Supports both old (projectId, scheduledFor, options) and new (options) signatures
*/
async createScheduledCampaign(
projectIdOrOptions: string | CampaignFactoryOptions,
scheduledFor?: Date,
options?: Partial<CampaignFactoryOptions>,
) {
// Support both calling conventions
let campaignOptions: CampaignFactoryOptions;
if (typeof projectIdOrOptions === 'string') {
// Old signature: createScheduledCampaign(projectId, scheduledFor, options)
const projectId = projectIdOrOptions;
campaignOptions = {
projectId,
...options,
scheduledFor: scheduledFor || new Date(Date.now() + 24 * 60 * 60 * 1000),
};
} else {
// New signature: createScheduledCampaign(options)
campaignOptions = projectIdOrOptions;
campaignOptions.scheduledFor = campaignOptions.scheduledFor || new Date(Date.now() + 24 * 60 * 60 * 1000);
}
return this.createCampaign({
...campaignOptions,
status: CampaignStatus.SCHEDULED,
});
}
/**
* Create an email
* Supports both old (projectId, contactId, options) and new (options) signatures
*/
async createEmail(
projectIdOrOptions:
| string
| {
projectId: string;
contactId: string;
subject?: string;
body?: string;
from?: string;
status?: EmailStatus;
sourceType?: EmailSourceType;
templateId?: string | null;
campaignId?: string | null;
sentAt?: Date | null;
messageId?: string | null;
openedAt?: Date | null;
clickedAt?: Date | null;
opens?: number;
clicks?: number;
error?: string | null;
},
contactId?: string,
additionalOptions?: Partial<{
subject?: string;
body?: string;
from?: string;
status?: EmailStatus;
sourceType?: EmailSourceType;
templateId?: string | null;
campaignId?: string | null;
sentAt?: Date | null;
messageId?: string | null;
openedAt?: Date | null;
clickedAt?: Date | null;
opens?: number;
clicks?: number;
error?: string | null;
}>,
) {
// Support both calling conventions
let options: {
projectId: string;
contactId: string;
subject?: string;
body?: string;
from?: string;
status?: EmailStatus;
sourceType?: EmailSourceType;
templateId?: string | null;
campaignId?: string | null;
sentAt?: Date | null;
messageId?: string | null;
openedAt?: Date | null;
clickedAt?: Date | null;
opens?: number;
clicks?: number;
error?: string | null;
};
if (typeof projectIdOrOptions === 'string') {
// Old signature: createEmail(projectId, contactId, options)
if (!contactId) {
throw new Error('contactId is required when using old signature');
}
options = {
projectId: projectIdOrOptions,
contactId,
...additionalOptions,
};
} else {
// New signature: createEmail(options)
options = projectIdOrOptions;
}
// Automatically determine sourceType based on context if not provided
let sourceType = options.sourceType;
if (!sourceType) {
if (options.campaignId) {
sourceType = EmailSourceType.CAMPAIGN;
} else if (options.templateId) {
sourceType = EmailSourceType.WORKFLOW;
} else {
sourceType = EmailSourceType.TRANSACTIONAL;
}
}
return this.prisma.email.create({
data: {
projectId: options.projectId,
contactId: options.contactId,
subject: options.subject || 'Test Email',
body: options.body || '<p>Test email body</p>',
from: options.from || '[email protected]',
status: options.status || EmailStatus.PENDING,
sourceType,
templateId: options.templateId,
campaignId: options.campaignId,
sentAt: options.sentAt,
messageId: options.messageId,
openedAt: options.openedAt,
clickedAt: options.clickedAt,
opens: options.opens,
clicks: options.clicks,
error: options.error,
},
});
}
/**
* Create a workflow with trigger step (matches WorkflowService.create behavior)
*/
async createWorkflow(options: WorkflowFactoryOptions) {
return this.prisma.$transaction(async tx => {
const workflow = await tx.workflow.create({
data: {
projectId: options.projectId,
name: options.name || `Workflow ${uniqueId()}`,
enabled: options.enabled ?? false,
triggerType: options.triggerType || WorkflowTriggerType.EVENT,
triggerConfig: options.triggerConfig || {eventName: 'contact.created'},
allowReentry: options.allowReentry ?? false,
},
});
// Create trigger step (required for workflow to function)
await tx.workflowStep.create({
data: {
workflowId: workflow.id,
type: WorkflowStepType.TRIGGER,
name: 'Trigger',
position: {x: 0, y: 0},
config: options.triggerConfig || {eventName: 'contact.created'},
},
});
return workflow;
});
}
/**
* Create a workflow step
*/
async createWorkflowStep(options: WorkflowStepFactoryOptions) {
// Build config based on step type
let config = options.config;
if (!config) {
switch (options.type) {
case WorkflowStepType.SEND_EMAIL:
config = {templateId: options.templateId || null};
break;
case WorkflowStepType.DELAY:
config = {amount: 24, unit: 'hours'};
break;
case WorkflowStepType.WAIT_FOR_EVENT:
config = {eventName: 'test.event', timeout: 3600};
break;
default:
config = {};
}
}
return this.prisma.workflowStep.create({
data: {
workflowId: options.workflowId,
type: options.type || WorkflowStepType.SEND_EMAIL,
name: options.name || `Step ${uniqueId()}`,
position: options.position || {x: 0, y: 0},
config,
templateId: options.templateId,
},
});
}
/**
* Create a workflow execution
*/
async createWorkflowExecution(
workflowId: string,
contactId: string,
overrides: {
status?: WorkflowExecutionStatus;
context?: Record<string, unknown>;
} = {},
) {
return this.prisma.workflowExecution.create({
data: {
workflowId,
contactId,
status: overrides.status || WorkflowExecutionStatus.RUNNING,
context: overrides.context || {},
},
});
}
/**
* Create a complete workflow with steps
*/
async createWorkflowWithSteps(
projectId: string,
steps: Array<{
type: WorkflowStepType;
delay?: number;
timeout?: number;
templateId?: string;
config?: unknown;
}>,
) {
const workflow = await this.createWorkflow({projectId});
const createdSteps = [];
for (let i = 0; i < steps.length; i++) {
const stepData = steps[i];
// Build config based on provided data or step type
let config = stepData.config;
if (!config) {
switch (stepData.type) {
case WorkflowStepType.SEND_EMAIL:
config = {templateId: stepData.templateId || null};
break;
case WorkflowStepType.DELAY:
config = {amount: stepData.delay || 24, unit: 'hours'};
break;
case WorkflowStepType.WAIT_FOR_EVENT:
config = {
eventName: 'test.event',
timeout: stepData.timeout || 3600,
};
break;
default:
config = {};
}
}
const step = await this.createWorkflowStep({
workflowId: workflow.id,
type: stepData.type,
name: `Step ${i + 1}`,
position: {x: i * 100, y: 0},
config,
templateId: stepData.templateId,
});
createdSteps.push(step);
}
return {workflow, steps: createdSteps};
}
/**
* Create a segment
*/
async createSegment(
projectId: string,
overrides: {
name?: string;
filters?: unknown;
trackMembership?: boolean;
} = {},
) {
return this.prisma.segment.create({
data: {
projectId,
name: overrides.name || `Segment ${uniqueId()}`,
filters: overrides.filters || [],
trackMembership: overrides.trackMembership ?? false,
},
});
}
/**
* Create an event
*/
async createEvent(
projectId: string,
contactId: string,
overrides: {
event?: string;
data?: Record<string, unknown>;
} = {},
) {
return this.prisma.event.create({
data: {
projectId,
contactId,
event: overrides.event || 'test.event',
data: overrides.data || {},
},
});
}
}
// Export lazy-initialized singleton instance
let factoriesInstance: TestFactories | null = null;
export const factories = new Proxy({} as TestFactories, {
get(target, prop) {
if (!factoriesInstance) {
factoriesInstance = new TestFactories();
}
return factoriesInstance[prop as keyof TestFactories];
},
});
+9
View File
@@ -0,0 +1,9 @@
/**
* Test helpers export
* Centralized export of all test utilities
*/
export * from './database';
export * from './factories';
export * from './time';
export * from './jobs';
+194
View File
@@ -0,0 +1,194 @@
import { vi } from 'vitest';
import { Queue, Worker, Job } from 'bullmq';
/**
* Job testing helper
* Provides utilities to test BullMQ job processors without Redis
*/
export interface MockJob<T = any> {
id: string;
data: T;
attemptsMade: number;
processedOn?: number;
finishedOn?: number;
returnvalue?: any;
failedReason?: string;
}
/**
* Create a mock BullMQ job
*/
export function createMockJob<T>(data: T, options: Partial<MockJob<T>> = {}): Job<T> {
const mockJob = {
id: options.id || `job-${Date.now()}`,
data,
attemptsMade: options.attemptsMade || 0,
processedOn: options.processedOn,
finishedOn: options.finishedOn,
returnvalue: options.returnvalue,
failedReason: options.failedReason,
// Mock methods
updateProgress: vi.fn(),
log: vi.fn(),
moveToCompleted: vi.fn(),
moveToFailed: vi.fn(),
remove: vi.fn(),
retry: vi.fn(),
} as unknown as Job<T>;
return mockJob;
}
/**
* Mock queue for testing job creation
*/
export class MockQueue<T = any> {
private jobs: Array<{ name?: string; data: T; opts?: any }> = [];
async add(name: string | T, data?: T | any, opts?: any) {
// Handle both queue.add(data) and queue.add(name, data) patterns
const jobName = typeof name === 'string' ? name : undefined;
const jobData = typeof name === 'string' ? data : name;
const jobOpts = typeof name === 'string' ? opts : data;
this.jobs.push({
name: jobName,
data: jobData,
opts: jobOpts,
});
return createMockJob(jobData, { id: `mock-${this.jobs.length}` });
}
getJobs() {
return this.jobs;
}
getJobsByName(name: string) {
return this.jobs.filter((job) => job.name === name);
}
clear() {
this.jobs = [];
}
async close() {
// No-op for mock
}
}
/**
* Create mock queues for testing
*/
export function createMockQueues() {
return {
email: new MockQueue(),
campaign: new MockQueue(),
scheduledCampaign: new MockQueue(),
workflow: new MockQueue(),
import: new MockQueue(),
segmentCount: new MockQueue(),
domainVerification: new MockQueue(),
};
}
/**
* Job processor test helper
* Allows testing job processors in isolation
*/
export class JobProcessorTester<T = any> {
private processor: (job: Job<T>) => Promise<any>;
constructor(processor: (job: Job<T>) => Promise<any>) {
this.processor = processor;
}
/**
* Process a job with test data
*/
async process(data: T, options: Partial<MockJob<T>> = {}) {
const job = createMockJob(data, options);
return this.processor(job);
}
/**
* Process multiple jobs
*/
async processMany(dataArray: T[], options: Partial<MockJob<T>> = {}) {
const results = [];
for (const data of dataArray) {
const result = await this.process(data, options);
results.push(result);
}
return results;
}
}
/**
* Create a job processor tester
*/
export function createJobTester<T = any>(processor: (job: Job<T>) => Promise<any>) {
return new JobProcessorTester<T>(processor);
}
/**
* Mock external services for job testing
*/
export function createServiceMocks() {
return {
// Mock SES (email sending)
ses: {
sendEmail: vi.fn().mockResolvedValue({ MessageId: 'mock-message-id' }),
sendRawEmail: vi.fn().mockResolvedValue({ MessageId: 'mock-message-id' }),
},
// Mock S3 (file storage)
s3: {
upload: vi.fn().mockResolvedValue({ Location: 'https://mock-s3.com/file.jpg' }),
getSignedUrl: vi.fn().mockResolvedValue('https://mock-s3.com/signed-url'),
deleteObject: vi.fn().mockResolvedValue({}),
},
// Mock Stripe (billing)
stripe: {
customers: {
create: vi.fn().mockResolvedValue({ id: 'cus_mock' }),
retrieve: vi.fn().mockResolvedValue({ id: 'cus_mock' }),
},
subscriptions: {
create: vi.fn().mockResolvedValue({ id: 'sub_mock' }),
update: vi.fn().mockResolvedValue({ id: 'sub_mock' }),
},
},
// Mock Redis
redis: {
get: vi.fn().mockResolvedValue(null),
set: vi.fn().mockResolvedValue('OK'),
del: vi.fn().mockResolvedValue(1),
incr: vi.fn().mockResolvedValue(1),
expire: vi.fn().mockResolvedValue(1),
},
};
}
/**
* Wait for jobs to complete (useful in integration tests with real queues)
*/
export async function waitForJobs(queue: Queue, timeout = 5000): Promise<void> {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const counts = await queue.getJobCounts('waiting', 'active', 'delayed');
const pending = counts.waiting + counts.active + counts.delayed;
if (pending === 0) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(`Jobs did not complete within ${timeout}ms`);
}
+125
View File
@@ -0,0 +1,125 @@
import { vi } from 'vitest';
import dayjs from 'dayjs';
/**
* Time control helper for testing time-dependent functionality
* Provides utilities to freeze time, advance time, and control dayjs
*/
export class TimeControl {
private currentTime: Date | null = null;
/**
* Freeze time at a specific date
* @param date Date to freeze at (defaults to 2025-01-01 12:00:00 UTC)
*/
freeze(date?: Date | string) {
const freezeDate = date ? new Date(date) : new Date('2025-01-01T12:00:00.000Z');
this.currentTime = freezeDate;
vi.useFakeTimers();
vi.setSystemTime(freezeDate);
return freezeDate;
}
/**
* Advance time by specified duration
* @param ms Milliseconds to advance
*/
advance(ms: number) {
if (!this.currentTime) {
throw new Error('Time not frozen. Call freeze() first.');
}
vi.advanceTimersByTime(ms);
this.currentTime = new Date(this.currentTime.getTime() + ms);
return this.currentTime;
}
/**
* Advance time to a specific date
* @param date Target date
*/
advanceTo(date: Date | string) {
const targetDate = new Date(date);
if (!this.currentTime) {
throw new Error('Time not frozen. Call freeze() first.');
}
const diff = targetDate.getTime() - this.currentTime.getTime();
if (diff < 0) {
throw new Error('Cannot advance to a date in the past');
}
return this.advance(diff);
}
/**
* Get current frozen time
*/
now(): Date {
if (!this.currentTime) {
throw new Error('Time not frozen. Call freeze() first.');
}
return this.currentTime;
}
/**
* Restore real time
*/
restore() {
vi.useRealTimers();
this.currentTime = null;
}
/**
* Helper methods for common time operations
*/
helpers = {
/** Advance time by seconds */
advanceSeconds: (seconds: number) => this.advance(seconds * 1000),
/** Advance time by minutes */
advanceMinutes: (minutes: number) => this.advance(minutes * 60 * 1000),
/** Advance time by hours */
advanceHours: (hours: number) => this.advance(hours * 60 * 60 * 1000),
/** Advance time by days */
advanceDays: (days: number) => this.advance(days * 24 * 60 * 60 * 1000),
/** Get a date relative to frozen time */
relative: (amount: number, unit: 'second' | 'minute' | 'hour' | 'day') => {
if (!this.currentTime) {
throw new Error('Time not frozen. Call freeze() first.');
}
return dayjs(this.currentTime).add(amount, unit).toDate();
},
};
}
/**
* Create a new TimeControl instance for a test
*/
export function createTimeControl() {
return new TimeControl();
}
/**
* Helper to run a test with frozen time
*/
export async function withFrozenTime<T>(
date: Date | string,
fn: (timeControl: TimeControl) => T | Promise<T>
): Promise<T> {
const timeControl = new TimeControl();
timeControl.freeze(date);
try {
return await fn(timeControl);
} finally {
timeControl.restore();
}
}