|
| 1 | +import { getClient, getMainCarrier, SentrySpan, setCurrentClient, spanToJSON } from '@sentry/core'; |
| 2 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 3 | +import { addWebVitalsToSpan, startTrackingWebVitals } from '../../src/web-vitals/tracking'; |
| 4 | +import { getDefaultClientOptions, TestClient } from '../utils/TestClient'; |
| 5 | + |
| 6 | +// Lives in its own file rather than alongside the regular-page-load case: the paint observers, the |
| 7 | +// `instrumented` registry and the visibility watcher are all module-level singletons that can only |
| 8 | +// be armed once, so a second scenario in the same file would reuse the first one's state. |
| 9 | + |
| 10 | +interface ObserverRegistration { |
| 11 | + callback: (list: PerformanceObserverEntryList) => void; |
| 12 | + buffered: boolean; |
| 13 | +} |
| 14 | + |
| 15 | +const observers: ObserverRegistration[] = []; |
| 16 | +const emittedEntries: PerformanceEntry[] = []; |
| 17 | + |
| 18 | +function deliver(callback: (list: PerformanceObserverEntryList) => void, entries: PerformanceEntry[]): void { |
| 19 | + callback({ getEntries: () => entries } as PerformanceObserverEntryList); |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Models the two things the real `PerformanceObserver` does that matter here: entries go to every |
| 24 | + * observer already listening, and an observer that registers later with `buffered: true` is replayed |
| 25 | + * the ones it missed. That difference is the point of this test: our paint observer is listening |
| 26 | + * during the prerender, web-vitals' only registers after activation. |
| 27 | + */ |
| 28 | +class MockPerformanceObserver { |
| 29 | + public static supportedEntryTypes = ['paint']; |
| 30 | + |
| 31 | + private _registration: ObserverRegistration; |
| 32 | + |
| 33 | + public constructor(callback: (list: PerformanceObserverEntryList) => void) { |
| 34 | + this._registration = { callback, buffered: false }; |
| 35 | + observers.push(this._registration); |
| 36 | + } |
| 37 | + |
| 38 | + public observe(options?: { buffered?: boolean }): void { |
| 39 | + this._registration.buffered = !!options?.buffered; |
| 40 | + |
| 41 | + if (this._registration.buffered && emittedEntries.length) { |
| 42 | + deliver(this._registration.callback, emittedEntries); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public disconnect(): void { |
| 47 | + // noop |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +function emitPaintEntries(entries: PerformanceEntry[]): void { |
| 52 | + emittedEntries.push(...entries); |
| 53 | + |
| 54 | + for (const { callback } of observers) { |
| 55 | + deliver(callback, entries); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +function flush(): Promise<void> { |
| 60 | + return new Promise(resolve => setTimeout(resolve, 0)); |
| 61 | +} |
| 62 | + |
| 63 | +describe('startTrackingWebVitals', () => { |
| 64 | + const realPerformance = globalThis.performance; |
| 65 | + |
| 66 | + beforeEach(() => { |
| 67 | + getMainCarrier().__SENTRY__ = undefined; |
| 68 | + |
| 69 | + const client = new TestClient(getDefaultClientOptions({ tracesSampleRate: 1 })); |
| 70 | + setCurrentClient(client); |
| 71 | + client.init(); |
| 72 | + }); |
| 73 | + |
| 74 | + afterEach(() => { |
| 75 | + vi.unstubAllGlobals(); |
| 76 | + vi.restoreAllMocks(); |
| 77 | + }); |
| 78 | + |
| 79 | + it('rebases fp and fcp against activationStart for prerendered pages', async () => { |
| 80 | + // The document is still sitting in the prerender buffer, so `activationStart` reads 0. It only |
| 81 | + // becomes the real activation time once the user navigates to the page. |
| 82 | + const navigationEntry = { type: 'navigate', responseStart: 1, activationStart: 0 } as PerformanceNavigationTiming; |
| 83 | + const documentStub = { prerendering: true, readyState: 'complete', visibilityState: 'visible' }; |
| 84 | + const pageListeners: Record<string, Array<() => void>> = {}; |
| 85 | + |
| 86 | + vi.stubGlobal('PerformanceObserver', MockPerformanceObserver); |
| 87 | + vi.stubGlobal('addEventListener', (type: string, listener: () => void) => { |
| 88 | + (pageListeners[type] ??= []).push(listener); |
| 89 | + }); |
| 90 | + vi.stubGlobal('removeEventListener', vi.fn()); |
| 91 | + vi.stubGlobal('document', documentStub); |
| 92 | + vi.stubGlobal('performance', { |
| 93 | + timeOrigin: realPerformance.timeOrigin, |
| 94 | + now: () => realPerformance.now(), |
| 95 | + getEntries: () => [], |
| 96 | + getEntriesByType: (type: string) => (type === 'navigation' ? [navigationEntry] : []), |
| 97 | + }); |
| 98 | + |
| 99 | + const cleanupWebVitals = startTrackingWebVitals({ trackCls: false, trackLcp: false, client: getClient()! }); |
| 100 | + |
| 101 | + // The page paints while it is still prerendering, 5s into the prerender navigation. Our paint |
| 102 | + // observer sees this right away; web-vitals' `onFCP` is still waiting on `prerenderingchange`. |
| 103 | + emitPaintEntries([ |
| 104 | + { entryType: 'paint', name: 'first-paint', duration: 0, startTime: 5012, toJSON: () => ({}) }, |
| 105 | + { entryType: 'paint', name: 'first-contentful-paint', duration: 0, startTime: 5018, toJSON: () => ({}) }, |
| 106 | + ] as PerformanceEntry[]); |
| 107 | + await flush(); |
| 108 | + |
| 109 | + // The user clicks the link and the page activates 5s into the prerender navigation, so the |
| 110 | + // paints they actually perceived happened 12ms and 18ms after the click. |
| 111 | + documentStub.prerendering = false; |
| 112 | + navigationEntry.activationStart = 5000; |
| 113 | + pageListeners.prerenderingchange?.forEach(listener => listener()); |
| 114 | + await flush(); |
| 115 | + |
| 116 | + cleanupWebVitals(); |
| 117 | + |
| 118 | + const pageloadSpan = new SentrySpan({ op: 'pageload', name: '/', sampled: true }); |
| 119 | + addWebVitalsToSpan(pageloadSpan, { |
| 120 | + recordClsOnPageloadSpan: true, |
| 121 | + recordLcpOnPageloadSpan: true, |
| 122 | + spanStreamingEnabled: true, |
| 123 | + }); |
| 124 | + |
| 125 | + expect(spanToJSON(pageloadSpan).attributes['browser.web_vital.fp.value']).toBe(12); |
| 126 | + expect(spanToJSON(pageloadSpan).attributes['browser.web_vital.fcp.value']).toBe(18); |
| 127 | + }); |
| 128 | +}); |
0 commit comments