All source files

tests/consent.test.mjs

Download raw file

import test from 'node:test';
import assert from 'node:assert/strict';
import {
  CONSENT_STORAGE_KEY,
  CONSENT_POLICY_VERSION,
  readConsent,
  saveConsent,
  clearConsent,
  consentAllowsAnalytics,
  isAnalyticsAllowed,
  createTrackEvent,
  gtmScriptUrl,
  initConsentUi
} from '../src/consent.mjs';

function memoryStorage(initial = {}) {
  const values = new Map(Object.entries(initial));
  return {
    getItem(key) { return values.has(key) ? values.get(key) : null; },
    setItem(key, value) { values.set(key, String(value)); },
    removeItem(key) { values.delete(key); },
    dump() { return Object.fromEntries(values); }
  };
}

function acceptedRecord(overrides = {}) {
  return JSON.stringify({
    policyVersion: CONSENT_POLICY_VERSION,
    decision: 'accepted',
    timestamp: '2026-12-06T08:00:00.000Z',
    ...overrides
  });
}

function fakeDocument({locale = 'en', gtmId = 'GTM-TVV8RWFT', endpoint = ''} = {}) {
  const appended = [];
  const handlers = {accept: null, reject: null, settings: null};
  const banner = {
    hidden: true,
    focused: false,
    scrolled: false,
    querySelector(selector) {
      if (selector === '[data-consent-accept]') return {addEventListener: (_type, handler) => {handlers.accept = handler;}};
      if (selector === '[data-consent-reject]') return {addEventListener: (_type, handler) => {handlers.reject = handler;}};
      return null;
    },
    focus() { this.focused = true; },
    scrollIntoView() { this.scrolled = true; }
  };
  const status = {textContent: ''};
  const settings = {addEventListener(_type, handler) { handlers.settings = handler; }};
  const doc = {
    documentElement: {lang: locale === 'zh' ? 'zh-CN' : 'en'},
    getElementById(id) { return id === 'cookieBanner' ? banner : null; },
    querySelector(selector) {
      if (selector === 'meta[name="wordhint-gtm-id"]') return gtmId ? {getAttribute: () => gtmId} : null;
      if (selector === 'meta[name="wordhint-analytics-endpoint"]') return endpoint ? {getAttribute: () => endpoint} : null;
      return null;
    },
    querySelectorAll(selector) {
      if (selector === '[data-consent-status]') return [status];
      if (selector === '[data-cookie-settings]') return [settings];
      return [];
    },
    createElement() { return {}; },
    head: {appendChild(node) { appended.push(node); }}
  };
  return {doc, banner, status, handlers, appended};
}

test('consent records round-trip with policy version and timestamp', () => {
  const storage = memoryStorage();
  const before = new Date('2026-12-06T08:00:00.000Z');
  const record = saveConsent(storage, 'accepted', before);
  assert.deepEqual(record, {
    policyVersion: CONSENT_POLICY_VERSION,
    decision: 'accepted',
    timestamp: '2026-12-06T08:00:00.000Z'
  });
  assert.deepEqual(readConsent(storage), record);
  assert.equal(consentAllowsAnalytics(record), true);
  assert.equal(consentAllowsAnalytics({...record, decision: 'denied'}), false);
  assert.equal(clearConsent(storage), true);
  assert.equal(readConsent(storage), null);
});

test('malformed, stale-version, unknown-decision and missing-timestamp records fail closed', () => {
  const cases = [
    '{broken',
    JSON.stringify({policyVersion: '2025-01-01', decision: 'accepted', timestamp: '2026-12-06T08:00:00.000Z'}),
    JSON.stringify({policyVersion: CONSENT_POLICY_VERSION, decision: 'allow', timestamp: '2026-12-06T08:00:00.000Z'}),
    JSON.stringify({policyVersion: CONSENT_POLICY_VERSION, decision: 'accepted'})
  ];
  for (const raw of cases) {
    const storage = memoryStorage({[CONSENT_STORAGE_KEY]: raw});
    assert.equal(readConsent(storage), null, raw);
    assert.equal(isAnalyticsAllowed({localStorage: storage}), false, raw);
  }
});

test('storage failures are treated as no consent and never throw', () => {
  const storage = {
    getItem() { throw new DOMException('Denied', 'SecurityError'); },
    setItem() { throw new DOMException('Denied', 'SecurityError'); },
    removeItem() { throw new DOMException('Denied', 'SecurityError'); }
  };
  assert.equal(readConsent(storage), null);
  assert.equal(saveConsent(storage, 'accepted'), null);
  assert.equal(clearConsent(storage), false);
  assert.equal(isAnalyticsAllowed({localStorage: storage}), false);
});

test('missing or incomplete storage cannot claim a saved decision', () => {
  assert.equal(saveConsent(null, 'accepted'), null);
  assert.equal(saveConsent(undefined, 'accepted'), null);
  assert.equal(saveConsent({}, 'accepted'), null);
  assert.equal(clearConsent(null), false);
  assert.equal(clearConsent(undefined), false);
  assert.equal(clearConsent({}), false);
});

test('saveConsent only reports success after the stored value is read back', () => {
  const writeOnly = {setItem() {}, getItem() { return null; }};
  assert.equal(saveConsent(writeOnly, 'accepted', new Date('2026-12-06T08:00:00.000Z')), null);

  const tampering = memoryStorage();
  const originalSetItem = tampering.setItem;
  tampering.setItem = function (key, value) {
    originalSetItem.call(this, key, key === CONSENT_STORAGE_KEY ? value.replace('accepted', 'denied') : value);
  };
  assert.equal(saveConsent(tampering, 'accepted'), null);
});

test('clearConsent only reports success after absence is read back', () => {
  const storage = memoryStorage({[CONSENT_STORAGE_KEY]: acceptedRecord()});
  storage.removeItem = () => {};
  assert.equal(clearConsent(storage), false);
  assert.notEqual(readConsent(storage), null);
});

test('trackEvent only writes dataLayer after accepted consent', () => {
  const target = {};
  target.WordHintConsent = {isAnalyticsAllowed: () => false};
  const denied = createTrackEvent(target);
  denied('hint_viewed', {puzzle: 2, hint_step: 1, mode: 'daily'});
  assert.equal(target.dataLayer, undefined);

  target.WordHintConsent = {isAnalyticsAllowed: () => true};
  const accepted = createTrackEvent(target);
  accepted('hint_viewed', {puzzle: 2, hint_step: 1, mode: 'daily'});
  assert.deepEqual(target.dataLayer, [{event: 'hint_viewed', puzzle: 2, hint_step: 1, mode: 'daily'}]);
});

test('GTM loader is not injected before consent and uses the official URL after acceptance', () => {
  const before = fakeDocument({gtmId: 'GTM-TVV8RWFT'});
  const winBefore = {localStorage: memoryStorage()};
  const apiBefore = initConsentUi({document: before.doc, window: winBefore});
  assert.equal(apiBefore.isAnalyticsAllowed(), false);
  assert.equal(before.appended.length, 0);
  assert.equal(winBefore.dataLayer, undefined);
  assert.equal(before.banner.hidden, false);

  const after = fakeDocument({gtmId: 'GTM-TVV8RWFT'});
  const winAfter = {localStorage: memoryStorage({[CONSENT_STORAGE_KEY]: acceptedRecord()})};
  const apiAfter = initConsentUi({document: after.doc, window: winAfter});
  assert.equal(apiAfter.isAnalyticsAllowed(), true);
  assert.equal(after.appended.length, 1);
  assert.equal(after.appended[0].src, gtmScriptUrl('GTM-TVV8RWFT'));
  assert.equal(after.appended[0].async, true);
  assert.deepEqual(winAfter.dataLayer[0], {event: 'gtm.js', 'gtm.start': winAfter.dataLayer[0]['gtm.start']});
  assert.equal(typeof winAfter.trackEvent, 'function');
});

test('accept, reject and withdrawal update storage, banner and outbound adapter', () => {
  const {doc, banner, status, handlers} = fakeDocument({locale: 'zh', gtmId: 'GTM-TVV8RWFT'});
  const storage = memoryStorage();
  const win = {localStorage: storage};
  const api = initConsentUi({document: doc, window: win, now: () => new Date('2026-12-06T08:00:00.000Z')});

  handlers.accept();
  assert.equal(readConsent(storage).decision, 'accepted');
  assert.equal(banner.hidden, true);
  assert.equal(typeof win.trackEvent, 'function');
  assert.match(status.textContent, /允许分析/);

  api.withdraw();
  assert.equal(readConsent(storage), null);
  assert.equal(banner.hidden, false);
  assert.equal(win.trackEvent, null);
  assert.match(status.textContent, /尚未选择/);

  handlers.reject();
  assert.equal(readConsent(storage).decision, 'denied');
  assert.equal(banner.hidden, true);
  assert.equal(api.isAnalyticsAllowed(), false);
});

test('unavailable storage keeps the banner open and never loads analytics', () => {
  const {doc, banner, status, handlers} = fakeDocument({locale: 'en', gtmId: 'GTM-TVV8RWFT'});
  const win = {localStorage: {
    getItem() { throw new DOMException('Denied', 'SecurityError'); },
    setItem() { throw new DOMException('Denied', 'SecurityError'); },
    removeItem() { throw new DOMException('Denied', 'SecurityError'); }
  }};
  const api = initConsentUi({document: doc, window: win});
  handlers.accept();
  assert.equal(api.isAnalyticsAllowed(), false);
  assert.equal(banner.hidden, false);
  assert.match(status.textContent, /could not be saved/);
  assert.equal(win.trackEvent, undefined);
});

test('a localStorage getter that throws is fail-closed through the whole banner flow', () => {
  const {doc, banner, status, handlers, appended} = fakeDocument({locale: 'en', gtmId: 'GTM-TVV8RWFT'});
  const win = {};
  Object.defineProperty(win, 'localStorage', {
    configurable: true,
    get() { throw new DOMException('Denied', 'SecurityError'); }
  });
  const api = initConsentUi({document: doc, window: win});

  assert.equal(api.isAnalyticsAllowed(), false);
  handlers.accept();

  assert.equal(api.getConsent(), null);
  assert.equal(api.isAnalyticsAllowed(), false);
  assert.equal(banner.hidden, false);
  assert.equal(appended.length, 0);
  assert.notEqual(typeof win.trackEvent, 'function');
  assert.match(status.textContent, /could not be saved/);
});

test('withdraw reports a persistence failure instead of claiming no choice', () => {
  const {doc, banner, status} = fakeDocument({locale: 'zh', gtmId: 'GTM-TVV8RWFT'});
  const storage = memoryStorage({[CONSENT_STORAGE_KEY]: acceptedRecord()});
  const win = {localStorage: storage};
  const api = initConsentUi({document: doc, window: win});
  assert.equal(api.isAnalyticsAllowed(), true);
  assert.equal(typeof win.trackEvent, 'function');

  storage.removeItem = () => { throw new DOMException('Denied', 'SecurityError'); };
  api.withdraw();

  assert.equal(api.isAnalyticsAllowed(), false);
  assert.equal(win.trackEvent, null);
  assert.equal(banner.hidden, false);
  assert.match(status.textContent, /无法保存你的选择/);
  assert.doesNotMatch(status.textContent, /尚未选择/);
});