autotel
Version:
Write Once, Observe Anywhere
96 lines (94 loc) • 2.55 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
//#region src/event-testing.ts
/**
* Create an in-memory events collector for testing
*
* @example
* ```typescript
* const collector = createEventCollector()
*
* const events = new Event('test-service', { collector })
* events.trackEvent('application.submitted', { jobId: '123' })
*
* const event =collector.getEvents()
* expect(events).toHaveLength(1)
* expect(events[0].event).toBe('application.submitted')
* ```
*/
function createEventCollector() {
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 an events event was tracked
*
* @example
* ```typescript
* assertEventTracked({
* collector,
* eventName: 'application.submitted',
* attributes: { jobId: '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: 'email.delivery',
* 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
exports.assertEventTracked = assertEventTracked;
exports.assertOutcomeTracked = assertOutcomeTracked;
exports.createEventCollector = createEventCollector;
//# sourceMappingURL=event-testing.cjs.map