UNPKG

autotel

Version:
92 lines (91 loc) 2.39 kB
//#region src/metric-testing.ts /** * Create an in-memory metrics collector for testing * * @example * ```typescript * const collector = createMetricsCollector() * * const metrics = new Metric('test-service', { collector }) * metrics.trackEvent('order.completed', { orderId: '123' }) * * const event =collector.getEvents() * expect(events).toHaveLength(1) * expect(events[0].event).toBe('order.completed') * ``` */ function createMetricsCollector() { const events = []; const funnelSteps = []; const outcomes = []; const values = []; return { getEvents() { return [...events]; }, getFunnelSteps() { return [...funnelSteps]; }, getOutcomes() { return [...outcomes]; }, getValues() { return [...values]; }, clear() { events.length = 0; funnelSteps.length = 0; outcomes.length = 0; values.length = 0; }, recordEvent(event) { events.push(event); }, recordFunnelStep(step) { funnelSteps.push(step); }, recordOutcome(outcome) { outcomes.push(outcome); }, recordValue(value) { values.push(value); } }; } /** * Assert that a metric event was tracked * * @example * ```typescript * assertEventTracked({ * collector, * eventName: 'order.completed', * attributes: { orderId: '123' } * }) * ``` */ function assertEventTracked(options) { const matching = options.collector.getEvents().filter((e) => e.event === options.eventName); if (matching.length === 0) throw new Error(`No events found with name: ${options.eventName}`); if (options.attributes) { if (matching.filter((e) => Object.entries(options.attributes).every(([key, value]) => e.attributes && e.attributes[key] === value)).length === 0) throw new Error(`Event ${options.eventName} found but attributes don't match: ${JSON.stringify(options.attributes)}`); } } /** * Assert that an outcome was tracked * * @example * ```typescript * assertOutcomeTracked({ * collector, * operation: 'payment.process', * status: 'success' * }) * ``` */ function assertOutcomeTracked(options) { if (options.collector.getOutcomes().filter((o) => o.operation === options.operation && o.status === options.status).length === 0) throw new Error(`No outcomes found with operation: ${options.operation} and status: ${options.status}`); } //#endregion export { assertEventTracked, assertOutcomeTracked, createMetricsCollector }; //# sourceMappingURL=metric-testing.js.map