Cookie banner is part of the first render: in the server HTML, decided before the first paint; pages stay static
Until now CookieBanner rendered nothing until the page had hydrated and an effect had read the cookie, so on a first
visit it appeared late and became the LCP element on text pages (request from a client project, 2026-11-26).
- The banner is rendered on the server with `hidden`, followed by one inline script (consentBannerScript) that,
before the browser paints, shows it (no current decision) or keeps it hidden (current decision). It decides as
readConsentRecord does. A click on a banner button before hydration is kept and carried out once the page is live.
- The decision is read through a store (useSyncExternalStore): no hydration mismatch, the browser's value before
the next paint. One decision per document.
- Optional server read (ConsentProvider cookieValue, SiteProviders consentCookie): exact HTML, dynamic pages.
- CookieBanner firstPaint={false} keeps the old behaviour; nonce from SiteProviders / ConsentProvider / the prop.
- Nothing about consent changes: no tag earlier, Consent Mode default first, cookie, consent log, withdrawal.
Tests: test/consentFirstPaint.test.ts (server render, script against readConsentRecord, hydration with no warning,
decisions, tags), reference e2e (static HTML, painted before hydration, returning visitor, early click).
Docs: consent.md "First paint", frontend.md, security.md, AGENT.md, skills, changelog draft under 1.17.0.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
2f6a81acbf
commit
177620da57
@@ -0,0 +1,484 @@
|
||||
// @vitest-environment happy-dom
|
||||
/**
|
||||
* The cookie banner is part of the first render (1.17.0): in the server HTML, decided before the first paint, with
|
||||
* no hydration mismatch — and nothing about consent itself changes: no tag earlier, Consent Mode default first, the
|
||||
* consent log and the stored cookie as before.
|
||||
*/
|
||||
import { act, createElement, type ReactElement } from 'react'
|
||||
import { hydrateRoot, type Root } from 'react-dom/client'
|
||||
import { renderToString } from 'react-dom/server'
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { ConsentState } from '../src/modules/consent/categories.js'
|
||||
|
||||
import { Analytics } from '../src/modules/analytics/Analytics.js'
|
||||
import { ConsentProvider } from '../src/modules/consent/ConsentContext.js'
|
||||
import { resetConsentStore } from '../src/modules/consent/consentStore.js'
|
||||
import { CookieBanner } from '../src/modules/consent/CookieBanner.js'
|
||||
import { CookieButton } from '../src/modules/consent/CookieButton.js'
|
||||
import { consentBannerScript } from '../src/modules/consent/firstPaint.js'
|
||||
import { CONSENT_FALLBACK, CONSENT_FALLBACK_PL } from '../src/modules/consent/getConsentTexts.js'
|
||||
import { CONSENT_COOKIE, readConsentRecord, serializeConsent } from '../src/modules/consent/storage.js'
|
||||
import { SiteProviders } from '../src/modules/frontend/SiteProviders.js'
|
||||
|
||||
const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement
|
||||
|
||||
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const ACCEPT: ConsentState = { analytics: true, functional: true, marketing: true, necessary: true }
|
||||
const REJECT: ConsentState = { analytics: false, functional: false, marketing: false, necessary: true }
|
||||
const texts = { ...CONSENT_FALLBACK, version: 3 }
|
||||
const stored = (state: ConsentState, version = 3) => serializeConsent(state, version, 'id-1')
|
||||
|
||||
type TreeOptions = { analytics?: object; banner?: object; cookieValue?: null | string; logEndpoint?: string; nonce?: string; texts?: object }
|
||||
const tree = (o: TreeOptions = {}) =>
|
||||
h(
|
||||
ConsentProvider,
|
||||
{ cookieValue: o.cookieValue, logEndpoint: o.logEndpoint, nonce: o.nonce, texts: o.texts ?? texts },
|
||||
h('main', null, 'page'),
|
||||
h(CookieBanner, o.banner ?? {}),
|
||||
h(CookieButton),
|
||||
o.analytics ? h(Analytics, o.analytics) : null,
|
||||
)
|
||||
|
||||
const clearCookies = () => {
|
||||
for (const c of document.cookie.split('; ')) {
|
||||
const name = c.split('=')[0]
|
||||
if (name) {document.cookie = `${name}=;path=/;max-age=0`}
|
||||
}
|
||||
}
|
||||
/** Cookies that hold a value (happy-dom keeps a just-expired cookie, emptied, until the second is over). */
|
||||
const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1])
|
||||
const storedRaw = () => liveCookies().find((c) => c.startsWith(`${CONSENT_COOKIE}=`))?.split('=')[1]
|
||||
const setConsentCookie = (value: string) => {
|
||||
document.cookie = `${CONSENT_COOKIE}=${value};path=/`
|
||||
}
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root | undefined
|
||||
let errors: ReturnType<typeof vi.spyOn>
|
||||
/** Scripts the code under test adds to <head> (never really loaded). */
|
||||
let injected: string[]
|
||||
|
||||
beforeEach(() => {
|
||||
clearCookies()
|
||||
resetConsentStore()
|
||||
delete (window as { dataLayer?: unknown[] }).dataLayer
|
||||
delete (window as { fbq?: unknown }).fbq
|
||||
delete (window as { _fbq?: unknown })._fbq
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
errors = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
injected = []
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation((node) => {
|
||||
injected.push((node as HTMLScriptElement).src || 'inline')
|
||||
return node
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {act(() => root!.unmount())}
|
||||
root = undefined
|
||||
container.remove()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const banner = () => container.querySelector<HTMLElement>('[data-ipal="banner"]')
|
||||
const button = () => container.querySelector<HTMLElement>('[data-ipal="cookie-button"]')
|
||||
const scriptEl = () => container.querySelector<HTMLScriptElement>('[data-ipal="banner-script"]')
|
||||
const click = (name: string) => act(() => container.querySelector<HTMLElement>(`[data-ipal="${name}"]`)!.click())
|
||||
|
||||
/** What the browser does while parsing: run the inline script with itself as document.currentScript. */
|
||||
function runInlineScript(html: string) {
|
||||
const el = scriptEl()
|
||||
// happy-dom gives no text for a script that came in through innerHTML: take it from the HTML itself
|
||||
const code = /<script[^>]*data-ipal="banner-script"[^>]*>(?<code>.*?)<\/script>/s.exec(html)?.groups?.code
|
||||
if (!el || !code) {return}
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
new Function('document', code)({
|
||||
get cookie() {
|
||||
return document.cookie
|
||||
},
|
||||
currentScript: el,
|
||||
})
|
||||
}
|
||||
|
||||
/** Server HTML into the page, the inline script as the parser would run it, then hydration. */
|
||||
function load(o: { blocked?: boolean; serverCookie?: null | string } & TreeOptions = {}) {
|
||||
const node = tree({ ...o, cookieValue: o.serverCookie })
|
||||
// renderToString never reads document.cookie (the store's server snapshot): see 'the same HTML for every visitor'
|
||||
container.innerHTML = renderToString(node)
|
||||
const html = renderToString(node)
|
||||
if (!o.blocked) {runInlineScript(html)}
|
||||
const beforeHydration = { display: banner()?.style.display, hidden: banner()?.hasAttribute('hidden') }
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
return { beforeHydration, html }
|
||||
}
|
||||
const visibleBeforeHydration = (r: ReturnType<typeof load>) => r.beforeHydration.hidden === false && r.beforeHydration.display !== 'none'
|
||||
|
||||
describe('server render', () => {
|
||||
test('static page: the banner is in the HTML, hidden, with its script right after it; no button', () => {
|
||||
const html = renderToString(tree())
|
||||
expect(html).toMatch(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
|
||||
expect(html).toContain(CONSENT_FALLBACK.message.slice(0, 40))
|
||||
expect(html).toMatch(/<\/div><script[^>]*data-ipal="banner-script"[^>]*>\(function/)
|
||||
expect(html).toContain('.version===3')
|
||||
expect(html).not.toContain('data-ipal="cookie-button"')
|
||||
// the same HTML for every visitor: nothing in it depends on a cookie
|
||||
setConsentCookie(stored(ACCEPT))
|
||||
resetConsentStore()
|
||||
expect(renderToString(tree())).toBe(html)
|
||||
})
|
||||
|
||||
test('the page language decides the text', () => {
|
||||
const html = renderToString(tree({ texts: { ...CONSENT_FALLBACK_PL, version: 3 } }))
|
||||
expect(html).toContain('Używamy plików cookies')
|
||||
expect(html).toContain('Akceptuj wszystkie')
|
||||
})
|
||||
|
||||
test('server-read cookie with a current decision: no banner, no script, the button is in the HTML', () => {
|
||||
const html = renderToString(tree({ cookieValue: stored(REJECT) }))
|
||||
expect(html).not.toContain('data-ipal="banner"')
|
||||
expect(html).not.toContain('<script')
|
||||
expect(html).toContain('data-ipal="cookie-button"')
|
||||
})
|
||||
|
||||
test.each([
|
||||
['no cookie', null],
|
||||
['another policy version', stored(ACCEPT, 2)],
|
||||
['malformed', '%7Bnot-json'],
|
||||
['foreign content', encodeURIComponent('yes')],
|
||||
])('server-read cookie, %s: the banner is in the HTML, shown, without a script', (_label, cookieValue) => {
|
||||
const html = renderToString(tree({ cookieValue }))
|
||||
expect(html).toContain('data-ipal="banner"')
|
||||
expect(html).not.toMatch(/data-ipal="banner"[^>]*hidden/)
|
||||
expect(html).not.toContain('<script')
|
||||
expect(html).not.toContain('data-ipal="cookie-button"')
|
||||
})
|
||||
|
||||
test('firstPaint={false}: nothing in the HTML, as before 1.17.0', () => {
|
||||
const html = renderToString(tree({ banner: { firstPaint: false } }))
|
||||
expect(html).not.toContain('data-ipal="banner"')
|
||||
expect(html).not.toContain('<script')
|
||||
})
|
||||
|
||||
test('nonce: from the provider, or the banner prop', () => {
|
||||
expect(renderToString(tree({ nonce: 'n-1' }))).toMatch(/<script[^>]*nonce="n-1"/)
|
||||
expect(renderToString(tree({ banner: { nonce: 'n-2' }, nonce: 'n-1' }))).toMatch(/<script[^>]*nonce="n-2"/)
|
||||
})
|
||||
|
||||
test('SiteProviders passes its nonce and the optional server-read cookie', () => {
|
||||
const shell = { analytics: {}, consent: texts, jsonLd: [], lightboxTexts: {}, theme: {}, turnstileSiteKey: undefined }
|
||||
const site = (props: object) => renderToString(h(SiteProviders, { analytics: false, preconnect: false, shell, ...props }, h('main', null, 'page')))
|
||||
expect(site({ nonce: 'n-3' })).toMatch(/<script[^>]*data-ipal="banner-script"[^>]*nonce="n-3"|<script[^>]*nonce="n-3"[^>]*data-ipal="banner-script"/)
|
||||
const decided = site({ consentCookie: stored(REJECT) })
|
||||
expect(decided).not.toContain('data-ipal="banner"')
|
||||
expect(decided).toContain('data-ipal="cookie-button"')
|
||||
expect(site({ consentCookie: null })).not.toMatch(/data-ipal="banner"[^>]*hidden/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the first-paint script decides as readConsentRecord does', () => {
|
||||
const run = (cookie: string, version = 3) => {
|
||||
const b = { removeAttribute: (n: string) => void b.removed.push(n), removed: [] as string[], style: {} as Record<string, string> }
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
new Function('document', consentBannerScript({ version }))({ cookie, currentScript: { previousElementSibling: b } })
|
||||
return b.style.display === 'none' ? 'hidden' : b.removed.includes('hidden') ? 'shown' : 'untouched'
|
||||
}
|
||||
const raw = (cookie: string) =>
|
||||
cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
|
||||
?.split('=')[1]
|
||||
|
||||
test.each([
|
||||
['no cookie at all', ''],
|
||||
['other cookies only', 'a=1; theme=dark'],
|
||||
['a current decision', `a=1; ${CONSENT_COOKIE}=${stored(REJECT)}; b=2`],
|
||||
['a current decision, accept', `${CONSENT_COOKIE}=${stored(ACCEPT)}`],
|
||||
['an older policy version', `${CONSENT_COOKIE}=${stored(ACCEPT, 2)}`],
|
||||
['a newer policy version', `${CONSENT_COOKIE}=${stored(ACCEPT, 4)}`],
|
||||
['version as a string', `${CONSENT_COOKIE}=${encodeURIComponent(JSON.stringify({ state: ACCEPT, version: '3' }))}`],
|
||||
['malformed JSON', `${CONSENT_COOKIE}=%7Bnope`],
|
||||
['malformed encoding', `${CONSENT_COOKIE}=%E0%A4%A`],
|
||||
['empty value', `${CONSENT_COOKIE}=`],
|
||||
['JSON null', `${CONSENT_COOKIE}=null`],
|
||||
['a foreign value', `${CONSENT_COOKIE}=accepted`],
|
||||
['a cookie whose name only ends the same', `x-${CONSENT_COOKIE}=${stored(ACCEPT)}`],
|
||||
['a cookie whose name only starts the same', `${CONSENT_COOKIE}-old=${stored(ACCEPT)}`],
|
||||
['no state in the record (read as all refused)', `${CONSENT_COOKIE}=${encodeURIComponent(JSON.stringify({ version: 3 }))}`],
|
||||
['two cookies of the name: the first counts', `${CONSENT_COOKIE}=bad; ${CONSENT_COOKIE}=${stored(ACCEPT)}`],
|
||||
])('%s', (_label, cookie) => {
|
||||
const decided = readConsentRecord(raw(cookie), 3) !== null
|
||||
expect(run(cookie)).toBe(decided ? 'hidden' : 'shown')
|
||||
})
|
||||
|
||||
test('default version 1; no banner element next to the script: nothing happens, nothing throws', () => {
|
||||
expect(consentBannerScript()).toContain('.version===1')
|
||||
expect(run(`${CONSENT_COOKIE}=${serializeConsent(REJECT)}`, 1)).toBe('hidden')
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
expect(() => new Function('document', consentBannerScript())({ cookie: '', currentScript: null })).not.toThrow()
|
||||
})
|
||||
|
||||
test('cannot close its own <script>, reads and writes nothing else', () => {
|
||||
const script = consentBannerScript({ cookieName: '</script><script>alert(1)//', version: Number.NaN })
|
||||
expect(script).not.toContain('</script')
|
||||
expect(script).toContain('.version===1')
|
||||
const plain = consentBannerScript({ version: 3 })
|
||||
expect(plain).not.toMatch(/localStorage|sessionStorage|fetch|XMLHttpRequest|createElement|dataLayer|src=|cookie\s*=[^=]/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hydration', () => {
|
||||
test('first visit: visible before hydration, no hydration warning, the script leaves the tree', () => {
|
||||
const r = load()
|
||||
expect(visibleBeforeHydration(r)).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
expect(banner()!.hasAttribute('hidden')).toBe(false)
|
||||
expect(scriptEl()).toBeNull()
|
||||
expect(button()).toBeNull()
|
||||
})
|
||||
|
||||
test('returning visitor: never visible, no hydration warning, the button after hydration', () => {
|
||||
setConsentCookie(stored(REJECT))
|
||||
const r = load()
|
||||
expect(r.html).toContain('data-ipal="banner"') // static HTML: the same for everyone
|
||||
expect(r.beforeHydration).toEqual({ display: 'none', hidden: true })
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['policy version raised', stored(ACCEPT, 2)],
|
||||
['malformed cookie', '%7Bnope'],
|
||||
['foreign cookie', 'accepted'],
|
||||
])('%s: the banner asks again, from the first paint', (_label, value) => {
|
||||
setConsentCookie(value)
|
||||
const r = load()
|
||||
expect(visibleBeforeHydration(r)).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
expect(button()).toBeNull()
|
||||
})
|
||||
|
||||
test('script refused (CSP without the nonce) or no JavaScript: hidden until hydration, then as before', () => {
|
||||
const first = load({ blocked: true })
|
||||
expect(first.beforeHydration).toEqual({ display: '', hidden: true }) // what a no-JS visitor keeps seeing: no banner
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()!.hasAttribute('hidden')).toBe(false)
|
||||
act(() => root!.unmount())
|
||||
setConsentCookie(stored(REJECT))
|
||||
const back = load({ blocked: true })
|
||||
expect(back.beforeHydration.hidden).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
})
|
||||
|
||||
test('server-read cookie: the HTML is already right, no warning either way', () => {
|
||||
setConsentCookie(stored(REJECT))
|
||||
const decided = load({ serverCookie: stored(REJECT) })
|
||||
expect(decided.html).not.toContain('data-ipal="banner"')
|
||||
expect(decided.html).toContain('data-ipal="cookie-button"')
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
act(() => root!.unmount())
|
||||
clearCookies()
|
||||
const fresh = load({ serverCookie: null })
|
||||
expect(visibleBeforeHydration(fresh)).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['accept', ACCEPT],
|
||||
['reject', REJECT],
|
||||
])('a click on "%s" before hydration is carried out once the page is live', (action, state) => {
|
||||
const fetchMock = vi.fn((_url: string, _init: { body: string }) => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const node = tree({ logEndpoint: '/api/ipal/consent' })
|
||||
const html = renderToString(node)
|
||||
container.innerHTML = html
|
||||
runInlineScript(html)
|
||||
container.querySelector<HTMLElement>(`[data-ipal="${action}"]`)!.click() // nothing is listening but the script
|
||||
expect(banner()!.getAttribute('data-ipal-pending')).toBe(action)
|
||||
expect(liveCookies()).toEqual([]) // no decision is stored by the script itself
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(readConsentRecord(storedRaw(), 3)!.state).toEqual(state)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('early click on "settings" opens the settings; a click on the text or the link decides nothing', () => {
|
||||
const node = tree()
|
||||
const html = renderToString(node)
|
||||
container.innerHTML = html
|
||||
runInlineScript(html)
|
||||
banner()!.querySelector('p')!.click()
|
||||
expect(banner()!.hasAttribute('data-ipal-pending')).toBe(false)
|
||||
container.querySelector<HTMLElement>('[data-ipal="settings"]')!.click()
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(liveCookies()).toEqual([])
|
||||
expect(container.querySelector('#ipal-consent-title')).not.toBeNull()
|
||||
// live now: a click is handled by React alone, the script's listener stays out of it
|
||||
click('back')
|
||||
click('reject')
|
||||
expect(banner()).toBeNull()
|
||||
})
|
||||
|
||||
test('firstPaint={false}: appears with hydration, no warning', () => {
|
||||
const r = load({ banner: { firstPaint: false } })
|
||||
expect(r.html).not.toContain('data-ipal="banner"')
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
})
|
||||
|
||||
test('control: this harness does report a real hydration mismatch', () => {
|
||||
const node = tree()
|
||||
container.innerHTML = renderToString(node).replace('>page<', '>another page<')
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node, { onRecoverableError: (e) => console.error(e) })
|
||||
})
|
||||
expect(errors).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('decisions, reopening and withdrawal work as before', () => {
|
||||
const consentCookie = () => readConsentRecord(storedRaw(), 3)
|
||||
|
||||
test('reject → the button → the banner again → accept; the id stays, each decision is logged', () => {
|
||||
const fetchMock = vi.fn((_url: string, _init: { body: string }) => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
load({ logEndpoint: '/api/ipal/consent' })
|
||||
click('reject')
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
const first = consentCookie()!
|
||||
expect(first.state).toEqual(REJECT)
|
||||
expect(first.version).toBe(3)
|
||||
expect(first.id).toMatch(/^[0-9a-f]{24}$/)
|
||||
expect(Number.isNaN(Date.parse(first.timestamp))).toBe(false)
|
||||
|
||||
click('cookie-button')
|
||||
expect(banner()).not.toBeNull()
|
||||
expect(banner()!.hasAttribute('hidden')).toBe(false)
|
||||
expect(scriptEl()).toBeNull() // a banner made in the browser carries no script
|
||||
expect(button()).toBeNull()
|
||||
click('accept')
|
||||
expect(consentCookie()!.state).toEqual(ACCEPT)
|
||||
expect(consentCookie()!.id).toBe(first.id)
|
||||
|
||||
// the consent log: one POST per decision, the same body as before
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
const calls = fetchMock.mock.calls.map(([url, init]) => ({ ...(init as object), body: JSON.parse(init.body) as unknown, url }))
|
||||
expect(calls[0]).toEqual({ body: { id: first.id, state: REJECT, version: 3 }, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST', url: '/api/ipal/consent' })
|
||||
expect(calls[1].body).toEqual({ id: first.id, state: ACCEPT, version: 3 })
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('nothing is logged or written by rendering, hydrating or the script', () => {
|
||||
const fetchMock = vi.fn(() => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
load({ logEndpoint: '/api/ipal/consent' })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(liveCookies()).toEqual([])
|
||||
})
|
||||
|
||||
test('withdrawal: analytics cookies go, Google gets the update', () => {
|
||||
setConsentCookie(stored(ACCEPT))
|
||||
document.cookie = '_ga=GA1.1.1;path=/'
|
||||
document.cookie = '_ga_ABC=1;path=/'
|
||||
load()
|
||||
click('cookie-button')
|
||||
click('reject')
|
||||
expect(liveCookies().filter((c) => c.startsWith('_ga'))).toEqual([])
|
||||
expect(consentCookie()!.state).toEqual(REJECT)
|
||||
const update = [...(window.dataLayer as ArrayLike<unknown>[])].map((a) => Array.from(a)).find((a) => a[1] === 'update')!
|
||||
expect(update[2]).toMatchObject({ ad_storage: 'denied', analytics_storage: 'denied' })
|
||||
})
|
||||
|
||||
test('settings in the detailed window: choose a category, save', () => {
|
||||
load({ banner: { controls: 'switch', settings: 'detailed' } })
|
||||
click('settings')
|
||||
expect(container.querySelector('[data-ipal="consent-dialog"]')).not.toBeNull()
|
||||
act(() => container.querySelector<HTMLElement>('[data-ipal="category-analytics"] [role="switch"]')!.click())
|
||||
click('save')
|
||||
expect(consentCookie()!.state).toEqual({ ...REJECT, analytics: true })
|
||||
expect(banner()).toBeNull()
|
||||
})
|
||||
|
||||
test('a browser that refuses the cookie: the decision still holds for this page view', () => {
|
||||
load()
|
||||
Object.defineProperty(document, 'cookie', { configurable: true, get: () => '', set: () => {} })
|
||||
try {
|
||||
click('accept')
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
} finally {
|
||||
delete (document as { cookie?: string }).cookie
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('tags: nothing earlier than before', () => {
|
||||
const pixels = { clarityProjectId: 'clar', consentMode: 'basic', gtmContainerId: 'GTM-TEST', metaPixelId: '123' }
|
||||
const layer = () => [...((window.dataLayer ?? []))].map((entry) => (Object.prototype.toString.call(entry) === '[object Arguments]' ? Array.from(entry as ArrayLike<unknown>) : entry))
|
||||
|
||||
test('the server HTML holds one script, the banner one, and it names no tag', () => {
|
||||
const html = renderToString(tree({ analytics: pixels }))
|
||||
expect(html.match(/<script/g)).toHaveLength(1)
|
||||
expect(html).not.toMatch(/googletagmanager|facebook|clarity|GTM-TEST/)
|
||||
})
|
||||
|
||||
test('no decision: showing the banner at first paint loads no tag; Consent Mode default is all denied', () => {
|
||||
load({ analytics: pixels })
|
||||
expect(injected).toEqual([])
|
||||
expect(layer()).toEqual([['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied', wait_for_update: 500 })]])
|
||||
expect((window as { fbq?: unknown }).fbq).toBeUndefined()
|
||||
})
|
||||
|
||||
test('rejected earlier: still no tag after hydration', () => {
|
||||
setConsentCookie(stored(REJECT))
|
||||
load({ analytics: pixels })
|
||||
expect(injected).toEqual([])
|
||||
})
|
||||
|
||||
test('accepting in the banner: the default came first, then the update, then the tags', () => {
|
||||
load({ analytics: pixels })
|
||||
click('accept')
|
||||
const entries = layer()
|
||||
expect((entries[0] as unknown[]).slice(0, 2)).toEqual(['consent', 'default'])
|
||||
expect((entries[1] as unknown[]).slice(0, 2)).toEqual(['consent', 'update'])
|
||||
expect(entries[2]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(injected).toEqual(expect.arrayContaining(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST', 'https://connect.facebook.net/en_US/fbevents.js']))
|
||||
})
|
||||
|
||||
test('accepted earlier: Consent Mode default (the stored choice) is pushed before the Google tag starts', () => {
|
||||
setConsentCookie(stored(ACCEPT))
|
||||
load({ analytics: pixels })
|
||||
const entries = layer()
|
||||
expect(entries[0]).toEqual(['consent', 'default', expect.objectContaining({ ad_storage: 'granted', analytics_storage: 'granted' })])
|
||||
expect(entries.findIndex((e) => (e as { event?: string }).event === 'gtm.js')).toBeGreaterThan(0)
|
||||
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
|
||||
})
|
||||
|
||||
test("'advanced' (default): the Google tag loads before a decision as before, after the denied default", () => {
|
||||
load({ analytics: { gtmContainerId: 'GTM-TEST', metaPixelId: '123' } })
|
||||
const entries = layer()
|
||||
expect(entries[0]).toEqual(['consent', 'default', expect.objectContaining({ analytics_storage: 'denied' })])
|
||||
expect(entries[1]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(injected).toEqual(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST']) // no Meta Pixel without consent
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user