import { Observable, deepClone } from '@openobserve/browser-core' import { mockRumConfiguration, setupLocationObserver } from '../../../test' import type { LifeCycle } from '../lifeCycle' import { LifeCycleEventType } from '../lifeCycle' import type { RumConfiguration } from '../configuration' import type { RumMutationRecord } from '../../browser/domMutationObservable' import type { ViewCreatedEvent, ViewEvent, ViewOptions, ViewEndedEvent } from './trackViews' import { trackViews } from './trackViews' export type ViewTest = ReturnType interface ViewTrackingContext { lifeCycle: LifeCycle initialLocation?: string partialConfig?: Partial } export function setupViewTest( { lifeCycle, initialLocation, partialConfig }: ViewTrackingContext, initialViewOptions?: ViewOptions ) { const domMutationObservable = new Observable() const windowOpenObservable = new Observable() const configuration = mockRumConfiguration(partialConfig) const { locationChangeObservable, changeLocation } = setupLocationObserver(initialLocation) const { handler: viewUpdateHandler, getViewEvent: getViewUpdate, getHandledCount: getViewUpdateCount, } = spyOnViews() lifeCycle.subscribe(LifeCycleEventType.VIEW_UPDATED, viewUpdateHandler) const { handler: viewCreateHandler, getViewEvent: getViewCreate, getHandledCount: getViewCreateCount, } = spyOnViews() lifeCycle.subscribe(LifeCycleEventType.VIEW_CREATED, viewCreateHandler) const { handler: viewEndHandler, getViewEvent: getViewEnd, getHandledCount: getViewEndCount, } = spyOnViews() lifeCycle.subscribe(LifeCycleEventType.VIEW_ENDED, viewEndHandler) const { stop, startView, setViewName, setViewContext, setViewContextProperty, getViewContext, addTiming } = trackViews( location, lifeCycle, domMutationObservable, windowOpenObservable, configuration, locationChangeObservable, !configuration.trackViewsManually, initialViewOptions ) return { stop, startView, setViewContext, setViewContextProperty, getViewContext, changeLocation, setViewName, addTiming, getViewUpdate, getViewUpdateCount, getViewCreate, getViewCreateCount, getViewEnd, getViewEndCount, getLatestViewContext: () => ({ id: getViewCreate(getViewCreateCount() - 1).id, }), } } function spyOnViews() { const events: Event[] = [] return { handler: (event: Event) => { events.push( // Some properties can be mutated later deepClone(event) ) }, getViewEvent: (index: number) => events[index], getHandledCount: () => events.length, } }