import { getNavigationSource } from '@/lib/analytics'; /** jsdom's document.referrer is read-only; redefining it is the way in. */ function referrer(url: string) { Object.defineProperty(document, 'referrer', { value: url, configurable: true }); } const ORIGIN = 'http://localhost'; describe('getNavigationSource', () => { afterEach(() => referrer('')); it('attributes a visit from a location page to the place layer', () => { /* * The one this was added for. * * W2 published ~3,900 location pages whose entire purpose is to funnel * search traffic onto school pages. Before this case existed they fell * through to 'direct' — so the location layer's contribution was not * merely missing from the funnel, it was being counted in the bucket you * read as "typed the URL". The measurement that decides whether W2 worked * was confidently reporting the wrong answer. */ referrer(`${ORIGIN}/schools/barnet`); expect(getNavigationSource()).toBe('place'); }); it.each([ ['/schools/authority/kent', 'authority'], ['/schools/near/sw11', 'outcode'], ['/schools/brentwood/primary', 'phase variant'], ])('covers %s (%s)', (path) => { referrer(`${ORIGIN}${path}`); expect(getNavigationSource()).toBe('place'); }); it('still calls a school page "detail", one character away', () => { // /school/ and /schools/ differ by one letter and mean different things. // A prefix test written in the wrong order silently merges them. referrer(`${ORIGIN}/school/100010-brecknock-primary-school`); expect(getNavigationSource()).toBe('detail'); }); it.each([ ['/', 'search'], ['/rankings', 'rankings'], ['/compare?urns=1,2', 'compare'], ])('leaves %s attributed as %s', (path, expected) => { referrer(`${ORIGIN}${path}`); expect(getNavigationSource()).toBe(expected); }); it('treats an external referrer as direct', () => { // Umami records the real referrer on the pageview; this field is only // about internal navigation. referrer('https://www.google.com/search?q=schools+in+barnet'); expect(getNavigationSource()).toBe('direct'); }); it('treats no referrer as direct', () => { referrer(''); expect(getNavigationSource()).toBe('direct'); }); });