All source filestests/browser-suite.js
Download raw file
async (page, artifactsDir='artifacts/') => {
const base='http://127.0.0.1:4173';
const shots=String(artifactsDir).endsWith('/')?artifactsDir:artifactsDir+'/';
const checks=[],errors=[];
const check=(name,pass,detail='')=>checks.push({name,pass:!!pass,detail:String(detail)});
async function step(name,fn){try{await fn();check(name,true);}catch(e){check(name,false,e.message);}}
page.on('pageerror',e=>errors.push(e.message));
page.on('console',m=>{if(m.type()==='error')errors.push(m.text());});
await page.addInitScript(()=>{
const fixed=Date.parse('2026-12-05T12:00:00Z');
const NativeDate=Date;
class FixedDate extends NativeDate {constructor(...args){super(...(args.length?args:[fixed]));}static now(){return fixed;}}
window.Date=FixedDate;
window.__events=[];
window.addEventListener('wordhint:analytics',event=>window.__events.push(event.detail));
});
async function reset(path='/'){
await page.goto(base+path);await page.evaluate(()=>localStorage.clear());await page.reload();await page.waitForTimeout(120);
}
async function clearDraft(){
const count=await page.evaluate(()=>{const row=document.querySelectorAll('.tile-row')[document.querySelectorAll('#guessHistory li').length];return row?[...row.querySelectorAll('.tile-letter')].map(x=>x.textContent).join('').length:0;});
for(let i=0;i<count;i++)await page.locator('[data-key="BACK"]').click();
}
async function typeWord(word){
await clearDraft();
for(const letter of word.toUpperCase())await page.locator(`[data-key="${letter}"]`).click();
await page.locator('[data-key="ENTER"]').click();
}
await reset('/');
await step('Initial daily board, one hint and UTC',async()=>{
if(await page.locator('.tile').count()!==30)throw new Error('Expected 30 tiles');
if(await page.locator('#hintList li').count()!==1)throw new Error('Expected one initial hint');
if(!(await page.locator('#utcDate').textContent()).includes('2026'))throw new Error('UTC date missing');
await page.screenshot({path:shots+'desktop-daily.png',fullPage:true});
});
await step('Consent banner is accessible and does not cover the board',async()=>{
const analyticsConfigured=await page.evaluate(()=>!!document.querySelector('meta[name="wordhint-gtm-id"],meta[name="wordhint-analytics-endpoint"]'));
if(!analyticsConfigured){if(await page.locator('#cookieBanner').count())throw new Error('Consent banner rendered without an analytics channel');return;}
const banner=page.locator('#cookieBanner');
if(!await banner.isVisible())throw new Error('Consent banner missing when analytics is configured');
const structure=await banner.evaluate(el=>({role:el.getAttribute('role'),labelledby:el.getAttribute('aria-labelledby'),describedby:el.getAttribute('aria-describedby'),live:[...el.querySelectorAll('[aria-live]')].length,accept:!!el.querySelector('[data-consent-accept]'),reject:!!el.querySelector('[data-consent-reject]')}));
if(structure.role!=='region'||structure.labelledby!=='cookieBannerTitle'||!structure.describedby)throw new Error('Consent banner landmark/name missing: '+JSON.stringify(structure));
if(!structure.live||!structure.accept||!structure.reject)throw new Error('Consent banner live region or controls missing');
const overlap=await page.evaluate(()=>{const banner=document.querySelector('#cookieBanner').getBoundingClientRect();const board=document.querySelector('#board').getBoundingClientRect();return !(banner.bottom<=board.top||banner.top>=board.bottom||banner.right<=board.left||banner.left>=board.right);});
if(overlap)throw new Error('Consent banner overlaps the game board');
await page.locator('[data-consent-reject]').focus();
if(!await page.locator('[data-consent-reject]').evaluate(el=>document.activeElement===el))throw new Error('Consent control cannot receive keyboard focus');
});
await step('Consent gate blocks Google requests before choice and after withdrawal',async()=>{
const browser=page.context().browser();
const context=await browser.newContext({viewport:{width:375,height:812}});
const google=[];
const isGoogle=url=>/googletagmanager\.com|google-analytics\.com|analytics\.google\.com/.test(url);
context.on('request',request=>{if(isGoogle(request.url()))google.push(request.url());});
const consentPage=await context.newPage();
await consentPage.goto(base+'/');
await consentPage.waitForTimeout(600);
if(google.length)throw new Error('Google request before consent: '+google.join(', '));
if((await context.cookies()).some(cookie=>/^_ga/.test(cookie.name)))throw new Error('GA cookie written before consent');
if(await consentPage.evaluate(()=>localStorage.getItem('wordhint:analytics-consent:v1'))!==null)throw new Error('Consent choice stored before user action');
if(!await consentPage.locator('#cookieBanner').count()){await context.close();return;}
if(!await consentPage.locator('#cookieBanner').isVisible())throw new Error('Consent banner missing on a fresh browser');
const hasGtm=await consentPage.evaluate(()=>!!document.querySelector('meta[name="wordhint-gtm-id"]'));
await consentPage.locator('[data-consent-reject]').click();
await consentPage.waitForTimeout(200);
const denied=await consentPage.evaluate(()=>JSON.parse(localStorage.getItem('wordhint:analytics-consent:v1')));
if(denied.decision!=='denied'||!denied.timestamp||denied.policyVersion!=='2026-12-06')throw new Error('Denied choice not persisted with version/timestamp: '+JSON.stringify(denied));
await consentPage.reload();
await consentPage.waitForTimeout(400);
if(google.length)throw new Error('Google request after denied reload: '+google.join(', '));
if(await consentPage.locator('#cookieBanner').isVisible())throw new Error('Denied visitor was prompted again');
await consentPage.locator('[data-cookie-settings]').first().click();
if(!await consentPage.locator('#cookieBanner').isVisible())throw new Error('Change-choice entry did not reopen the banner');
await consentPage.locator('[data-consent-accept]').click();
await consentPage.waitForTimeout(1500);
if(hasGtm&&!google.some(url=>url.includes('googletagmanager.com/gtm.js')))throw new Error('GTM not requested after acceptance: '+google.join(', '));
const accepted=await consentPage.evaluate(()=>({record:JSON.parse(localStorage.getItem('wordhint:analytics-consent:v1')),trackEvent:typeof window.trackEvent,dataLayer:(window.dataLayer||[]).length}));
if(accepted.record.decision!=='accepted'||accepted.record.policyVersion!=='2026-12-06')throw new Error('Accepted choice not persisted');
if(hasGtm&&(accepted.trackEvent!=='function'||accepted.dataLayer<1))throw new Error('GTM dataLayer adapter missing after acceptance');
const cookiesBefore=(await context.cookies()).filter(cookie=>/^_ga/.test(cookie.name)).length;
const requestsBeforeReload=google.length;
await consentPage.locator('[data-cookie-settings]').first().click();
await consentPage.locator('[data-consent-reject]').click();
await consentPage.waitForTimeout(200);
await consentPage.reload();
await consentPage.waitForTimeout(500);
if(google.slice(requestsBeforeReload).some(isGoogle))throw new Error('Google request after withdrawal reload: '+google.slice(requestsBeforeReload).join(', '));
const cookiesAfter=(await context.cookies()).filter(cookie=>/^_ga/.test(cookie.name)).length;
if(cookiesAfter>cookiesBefore)throw new Error('GA cookie count increased after withdrawal reload');
await context.close();
});
await step('Invalid length and unknown word do not consume guesses',async()=>{
await typeWord('app');if(!(await page.locator('#feedback').textContent()).includes('五个'))throw new Error('Length feedback missing');
if(await page.locator('#guessHistory li').count()!==0)throw new Error('Short word consumed a guess');
await typeWord('xxxxx');if(!(await page.locator('#feedback').textContent()).includes('不在'))throw new Error('Word-list feedback missing');
if(await page.locator('#guessHistory li').count()!==0)throw new Error('Unknown word consumed a guess');
});
await reset('/');
await step('Repeated-letter scoring and one live summary per guess',async()=>{
await page.evaluate(()=>{window.__statusMutations=0;new MutationObserver(()=>window.__statusMutations++).observe(document.getElementById('feedback'),{childList:true,characterData:true,subtree:true});});
await typeWord('alley');
const statuses=await page.locator('.tile-row').first().locator('.tile').evaluateAll(tiles=>tiles.map(t=>['correct','present','absent'].find(s=>t.classList.contains(s))));
check('ALLEY vs APPLE statuses',JSON.stringify(statuses)===JSON.stringify(['correct','present','absent','present','absent']),JSON.stringify(statuses));
await page.waitForTimeout(250);
const contrasts=await page.locator('.tile-row').first().locator('.tile').evaluateAll(tiles=>{
const channels=rgb=>rgb.match(/[\d.]+/g).slice(0,3).map(Number);
const luminance=rgb=>{const values=channels(rgb).map(v=>{const c=v/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4);});return .2126*values[0]+.7152*values[1]+.0722*values[2];};
return tiles.map(tile=>{const style=getComputedStyle(tile),a=luminance(style.color),b=luminance(style.backgroundColor);return (Math.max(a,b)+.05)/(Math.min(a,b)+.05);});
});
check('Tile text contrast >=4.5:1',contrasts.every(ratio=>ratio>=4.5),JSON.stringify(contrasts));
if(await page.evaluate(()=>window.__statusMutations)!==1)throw new Error('Expected one live-region update');
});
await step('Hints remain manual after two misses and persist on reload',async()=>{
await typeWord('crane');
if(await page.locator('#hintList li').count()!==1)throw new Error('Hint auto-revealed');
if(!await page.locator('#hintOffer').isVisible())throw new Error('Hint offer missing');
await page.locator('#hintButton').click();if(await page.locator('#hintList li').count()!==2)throw new Error('Hint did not unlock');
await page.reload();if(await page.locator('#guessHistory li').count()!==2)throw new Error('Guesses not restored');
if(await page.locator('#hintList li').count()!==2)throw new Error('Hint step not restored');
});
await step('Solve, stats and spoiler-free share',async()=>{
await typeWord('apple');if(!await page.locator('#shareCard').isVisible())throw new Error('Share card missing');
if((await page.locator('#playedValue').textContent())!=='1')throw new Error('Played stat missing');
if((await page.locator('#winsValue').textContent())!=='1')throw new Error('Win stat missing');
const share=await page.locator('#sharePreview').textContent();
if(/apple|alley|crane/i.test(share))throw new Error('Share leaked a word');
await page.locator('#shareResult').click();
await page.screenshot({path:shots+'desktop-solved.png',fullPage:true});
});
await step('Analytics schema never leaks guesses, answers or state',async()=>{
const events=await page.evaluate(()=>window.__events);
if(!events.some(e=>e.name==='game_completed'))throw new Error('Completion event missing');
if(!events.some(e=>e.name==='result_shared'))throw new Error('Share event missing');
if(events.some(e=>['guess','answer','state','share_text'].some(key=>key in e)))throw new Error('Sensitive event field found');
if(!events.some(e=>e.name==='guess_submitted'&&e.attempt===3&&e.correct===true))throw new Error('Aggregate guess event missing');
});
await reset('/');
await step('Six wrong guesses lose and terminal input is ignored',async()=>{
for(const word of ['crane','sloth','plant','bloom','crisp','brave'])await typeWord(word);
if(await page.locator('#guessHistory li').count()!==6)throw new Error('Expected six guesses');
if(!(await page.locator('#feedback').textContent()).includes('机会用完'))throw new Error('Loss feedback missing');
if(!await page.locator('#submitGuess').isDisabled())throw new Error('Submit not disabled after loss');
if((await page.locator('#streakValue').textContent())!=='0')throw new Error('Loss should reset current streak');
});
await reset('/');
await step('Reveal answer preserves best but not current streak',async()=>{
await page.evaluate(()=>{localStorage.setItem('wordhint:stats:v1',JSON.stringify({version:1,played:4,wins:4,currentStreak:4,bestStreak:4,lastSolvedDay:'2026-12-04',distribution:{1:1,2:1,3:1,4:1,5:0,6:0},settledDays:['2026-12-01','2026-12-02','2026-12-03','2026-12-04']}));});
await page.reload();await page.locator('#revealButton').click();if(!await page.locator('#revealDialog').isVisible())throw new Error('Reveal confirmation missing');
await page.locator('#confirmReveal').click();
if((await page.locator('#streakValue').textContent())!=='0')throw new Error('Current streak should reset');
if((await page.locator('#bestValue').textContent())!=='4')throw new Error('Best streak should survive');
if(!(await page.locator('#feedback').textContent()).includes('APPLE'))throw new Error('Revealed answer missing');
});
await step('Corrupt daily save resets only daily board',async()=>{
const before=await page.locator('#playedValue').textContent();
await page.evaluate(()=>localStorage.setItem('wordhint:daily:v1','{broken'));await page.reload();
if(!await page.locator('#storageNotice').isVisible())throw new Error('Recovery notice missing');
if((await page.locator('#playedValue').textContent())!==before)throw new Error('Stats were reset with daily board');
});
await reset('/practice/');
await step('Practice new round and result do not touch daily stats',async()=>{
const first=await page.locator('#puzzleNumber').textContent();
await page.locator('#newPracticeTop').click();const second=await page.locator('#puzzleNumber').textContent();
if(first===second)throw new Error('Practice answer did not change');
await typeWord('apple');await typeWord('crane');
if(!await page.locator('#hintOffer').isVisible())throw new Error('Practice hint offer missing after two misses');
await page.locator('#hintButton').click();
const answer=await page.evaluate(async()=>{
const {PRACTICE_POOL}=await import('/assets/practice-data.mjs');
const hints=[...document.querySelectorAll('#hintList li')].map(item=>item.textContent).join('\n');
return PRACTICE_POOL.find(entry=>hints.includes(entry.clueZh)||hints.includes(entry.clueEn))?.word||'';
});
if(!answer)throw new Error('Current practice answer not found in practice pool');
await typeWord(answer);if(!await page.locator('#shareCard').isVisible())throw new Error('Practice completion missing');
const daily=await page.evaluate(()=>localStorage.getItem('wordhint:daily:v1'));
if(daily)throw new Error('Practice wrote daily state');
});
await reset('/en/');
await step('English UI and physical keyboard',async()=>{
if((await page.locator('html').getAttribute('lang'))!=='en')throw new Error('English lang missing');
if(await page.locator('#cookieBanner').count()){
const consentText=await page.locator('#cookieBanner').textContent();
if(!consentText.includes('Analytics cookie choice')||!consentText.includes('Allow analytics'))throw new Error('English consent copy missing or untranslated');
}
await page.keyboard.type('apple');await page.keyboard.press('Enter');
if(!await page.locator('#shareCard').isVisible())throw new Error('Physical keyboard solve failed');
if(!(await page.locator('#feedback').textContent()).includes('Solved'))throw new Error('English result missing');
});
await step('Offline after load remains playable',async()=>{
await reset('/');await page.context().setOffline(true);await typeWord('crane');
if(await page.locator('#guessHistory li').count()!==1)throw new Error('Offline guess failed');await page.context().setOffline(false);
});
await step('Reduced motion is respected',async()=>{
await page.emulateMedia({reducedMotion:'reduce'});await reset('/');
const duration=await page.locator('.tile').first().evaluate(el=>getComputedStyle(el).transitionDuration);
if(!duration.includes('0.00001')&&!duration.includes('0.01ms')&&!duration.includes('1e-05s')&&!duration.startsWith('0s'))throw new Error('Motion not reduced: '+duration);
});
const denied=await page.context().newPage();
await denied.addInitScript(()=>{const fail=()=>{throw new DOMException('Denied','SecurityError')};Storage.prototype.getItem=fail;Storage.prototype.setItem=fail;});
await step('Blocked storage remains playable',async()=>{
await denied.goto(base+'/');await denied.waitForTimeout(150);
if(!await denied.locator('#storageNotice').isVisible())throw new Error('Storage warning missing');
for(const letter of 'CRANE')await denied.locator(`[data-key="${letter}"]`).click();await denied.locator('[data-key="ENTER"]').click();
if(await denied.locator('#guessHistory li').count()!==1)throw new Error('Blocked storage prevented play');await denied.close();
});
for(const path of ['/','/practice/','/en/','/en/practice/']){
await page.goto(base+path);await page.setViewportSize({width:375,height:812});await page.waitForTimeout(100);
const width=await page.evaluate(()=>document.documentElement.scrollWidth);check('Mobile no horizontal overflow '+path,width<=375,width);
if(await page.locator('#cookieBanner').isVisible()){
const box=await page.locator('#cookieBanner').boundingBox();
check('Mobile consent banner inside viewport '+path,!!box&&box.x>=0&&box.x+box.width<=375.5,JSON.stringify(box));
}
await page.screenshot({path:shots+'mobile-'+(path==='/'?'daily':path==='/practice/'?'practice':path==='/en/'?'en-daily':'en-practice')+'.png',fullPage:true});
await page.setViewportSize({width:1280,height:800});
}
const browser=page.context().browser();
const touchContext=await browser.newContext({viewport:{width:375,height:812},isMobile:true,hasTouch:true});
const touchPage=await touchContext.newPage();
await step('Touch controls meet 44px primary and 24px dense-key targets',async()=>{
await touchPage.goto(base+'/');
const sizes=await touchPage.evaluate(()=>({submit:document.getElementById('submitGuess').getBoundingClientRect().height,key:[...document.querySelectorAll('.key')].map(el=>({w:el.getBoundingClientRect().width,h:el.getBoundingClientRect().height}))}));
if(sizes.submit<44)throw new Error('Primary touch target too small');
if(sizes.key.some(key=>key.w<24||key.h<44))throw new Error('Dense keyboard target too small');await touchContext.close();
});
check('No browser runtime or console errors',errors.length===0,errors.join(' | '));
return {checks,errors,summary:{passed:checks.filter(x=>x.pass).length,failed:checks.filter(x=>!x.pass).length,total:checks.length}};
}