test: suite completa di §11 e npm run verify verde

- html-validate su tutte le pagine; linkinator su astro preview (link, asset,
  CSS e ancore), con modalità --external per i siti esterni
- e2e Playwright: struttura e metadati di ogni pagina, 404, navigazione,
  sottomenu, menu mobile, ancore del vecchio sito, nessuna richiesta esterna,
  nessun cookie, localStorage vuoto, mappa solo dopo il clic, funzionamento
  senza JavaScript, modulo di contatto
- a11y: axe su tutte le pagine a 1440 e 390 px e negli stati interattivi,
  tastiera (skip link, sottomenu, menu mobile), focus visibile, testo al 200 %,
  reflow a 320 px, movimento ridotto
- check-compliance.mjs: P.IVA, link legali, risorse sicure, segnaposto,
  JSON-LD, sitemap, robots, .htaccess, badge e servizi, uso di
  «commercialista», riferimento L. 4/2013, budget
- fix: punti di interruzione in em, focus ciclico nel menu mobile,
  rel="noopener" sui link esterni del Markdown, numeri di telefono non spezzabili

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016zJ9ZWGKvoKoxYwbmnRKdJ
This commit is contained in:
Claude committed 2026-10-15 22:55:46 +00:00
1 parent 8ce77de137
commit 601d13cfaf
40 files changed
+1798 -114

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
/**
* Accessibilità automatica con axe-core (brief §11.3): tutte le pagine (lette dalla sitemap)
* a 1440 e 390 px, più gli stati interattivi (menu mobile e sottomenu aperti, mappa caricata).
* Criterio: zero violazioni «serious» o «critical» (WCAG 2.0/2.1 A e AA e buone pratiche);
* le violazioni minori sono comunque riportate nel messaggio d'errore e nelle annotazioni.
*/
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
import { ALL_PAGES, stubGoogle } from '../helpers/site';
const VIEWPORTS = [
{ name: 'desktop', width: 1440, height: 900 },
{ name: 'mobile', width: 390, height: 844 },
];
const TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'best-practice'];
async function audit(page: Page, where: string, include?: string, exclude?: string) {
let builder = new AxeBuilder({ page }).withTags(TAGS);
if (include) builder = builder.include(include);
if (exclude) builder = builder.exclude(exclude);
const results = await builder.analyze();
const blocking = results.violations.filter(
(v) => v.impact === 'serious' || v.impact === 'critical',
);
const report = results.violations.map(
(v) =>
`[${v.impact}] ${v.id}: ${v.help} — ${v.nodes
.slice(0, 5)
.map((n) => n.target.join(' '))
.join(' | ')}`,
);
if (report.length > 0) {
test.info().annotations.push({ type: 'axe', description: `${where}\n${report.join('\n')}` });
}
expect(blocking, `violazioni gravi di accessibilità in ${where}:\n${report.join('\n')}`).toEqual(
[],
);
}
for (const vp of VIEWPORTS) {
test.describe(`${vp.name} ${vp.width}px`, () => {
test.use({ viewport: { width: vp.width, height: vp.height } });
for (const path of ALL_PAGES) {
test(`axe: ${path}`, async ({ page }) => {
await page.goto(path, { waitUntil: 'networkidle' });
await audit(page, `${path} a ${vp.width}px`);
});
}
});
}
test.describe('stati interattivi', () => {
test('menu mobile aperto con sottomenu', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('/');
await page.locator('[data-menu-open]').click();
await page.locator('#menu-mobile [data-submenu-toggle]').click();
await audit(page, 'menu mobile aperto', '#menu-mobile');
});
test('sottomenu desktop aperto', async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto('/');
await page.locator('.nav [data-submenu-toggle]').click();
await audit(page, 'sottomenu desktop aperto', 'header');
});
test('mappa caricata', async ({ page }) => {
await stubGoogle(page);
await page.goto('/contatti/');
await page.locator('[data-map-load]').first().click();
await expect(page.locator('[data-map-consent] iframe')).toHaveCount(1);
// il contenuto dell'iframe è di Google (terze parti): si verifica solo il nostro markup
await audit(page, 'mappa caricata', '[data-map-consent]', '[data-map-consent] iframe');
});
});
+176
View File
@@ -0,0 +1,176 @@
/**
* Accessibilità da tastiera (brief §9.5, §11.3): link «salta al contenuto», sottomenu e menu
* mobile usabili con la tastiera, focus sempre visibile, testo ridimensionabile, reflow a 320 px.
*/
import { expect, test, type Page } from '@playwright/test';
import { ALL_PAGES } from '../helpers/site';
/** Vero se l'elemento attivo ha un indicatore di focus visibile (outline su sé o su ::after). */
async function focusIsVisible(page: Page): Promise<{ ok: boolean; what: string }> {
return page.evaluate(() => {
const el = document.activeElement as HTMLElement | null;
if (!el || el === document.body) return { ok: false, what: 'nessun elemento con il focus' };
const has = (s: CSSStyleDeclaration) =>
(s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0) ||
(s.boxShadow !== 'none' && s.boxShadow !== '');
const ok = has(getComputedStyle(el)) || has(getComputedStyle(el, '::after'));
const what = `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}.${String(el.className).split(' ')[0]} «${(el.textContent ?? '').trim().slice(0, 40)}»`;
return { ok, what };
});
}
test('il primo Tab porta al link «Vai al contenuto principale»', async ({ page }) => {
await page.goto('/studio/');
await page.keyboard.press('Tab');
const skip = page.locator('.skip-link');
await expect(skip).toBeFocused();
await expect(skip).toBeInViewport();
await expect(skip).toHaveText('Vai al contenuto principale');
await page.keyboard.press('Enter');
await expect(page.locator('main#contenuto')).toBeFocused();
// il Tab successivo prosegue all'interno del contenuto principale
await page.keyboard.press('Tab');
const insideMain = await page.evaluate(
() => document.querySelector('main')?.contains(document.activeElement) ?? false,
);
expect(insideMain, 'dopo il salto il focus prosegue nel contenuto').toBe(true);
});
test('sottomenu desktop: apertura con Invio, navigazione con Tab, chiusura con Esc', async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto('/');
const toggle = page.locator('.nav [data-submenu-toggle]');
const submenu = page.locator('#sottomenu-servizi');
// raggiunge il pulsante del sottomenu solo con la tastiera
for (let i = 0; i < 30; i++) {
await page.keyboard.press('Tab');
if (await toggle.evaluate((el) => el === document.activeElement)) break;
}
await expect(toggle).toBeFocused();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await page.keyboard.press('Enter');
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(submenu).toBeVisible();
await page.keyboard.press('Tab');
await expect(submenu.getByRole('link').first()).toBeFocused();
await page.keyboard.press('Escape');
await expect(submenu).toBeHidden();
await expect(toggle).toBeFocused();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
// uscendo dal sottomenu con Tab il sottomenu si chiude
await page.keyboard.press('Enter');
await expect(submenu).toBeVisible();
for (let i = 0; i < 7; i++) await page.keyboard.press('Tab');
await expect(submenu).toBeHidden();
});
test('menu mobile: apertura con Invio, focus intrappolato nel menu, chiusura con Esc', async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('/');
const toggle = page.locator('[data-menu-open]');
const menu = page.locator('#menu-mobile');
for (let i = 0; i < 10; i++) {
await page.keyboard.press('Tab');
if (await toggle.evaluate((el) => el === document.activeElement)) break;
}
await expect(toggle).toBeFocused();
await page.keyboard.press('Enter');
await expect(menu).toBeVisible();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(page.locator('[data-menu-close]')).toBeFocused();
for (let i = 0; i < 25; i++) {
await page.keyboard.press('Tab');
const inside = await menu.evaluate((m) => m.contains(document.activeElement));
expect(inside, `il focus resta nel menu aperto (Tab n. ${i + 1})`).toBe(true);
}
// il sottomenu si apre con la tastiera
await page.locator('#menu-mobile [data-submenu-toggle]').focus();
await page.keyboard.press('Enter');
await expect(page.locator('#menu-mobile-servizi')).toBeVisible();
await page.keyboard.press('Escape');
await expect(menu).toBeHidden();
await expect(toggle).toBeFocused();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
});
for (const path of ['/', '/servizi/', '/contatti/', '/dove-siamo/']) {
test(`focus visibile su ogni elemento raggiungibile con Tab in ${path}`, async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto(path);
const total = await page
.locator('a[href], button:not([disabled]), input, textarea, select, [tabindex="0"]')
.evaluateAll(
(els) =>
els.filter((e) => {
const r = (e as HTMLElement).getBoundingClientRect();
return r.width > 0 && r.height > 0 && (e as HTMLElement).tabIndex >= 0;
}).length,
);
expect(total).toBeGreaterThan(5);
const seen: string[] = [];
for (let i = 0; i < total; i++) {
await page.keyboard.press('Tab');
const { ok, what } = await focusIsVisible(page);
seen.push(what);
expect(ok, `focus non visibile su ${what} (Tab n. ${i + 1}) in ${path}`).toBe(true);
}
});
}
test('testo ingrandito al 200 % dalle impostazioni del browser: nessun contenuto tagliato', async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 900 });
// equivale a impostare «Dimensione carattere» a 32 px (il doppio di 16) nelle preferenze
const cdp = await page.context().newCDPSession(page);
await cdp.send('Page.enable');
await cdp.send('Page.setFontSizes', { fontSizes: { standard: 32, fixed: 26 } });
for (const path of ['/', '/servizi/contenzioso-tributario/', '/contatti/', '/note-legali/']) {
await page.goto(path);
const { overflow, fontSize } = await page.evaluate(() => ({
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
fontSize: parseFloat(getComputedStyle(document.body).fontSize),
}));
expect(fontSize, `dimensione del testo raddoppiata in ${path}`).toBeGreaterThanOrEqual(32);
expect(overflow, `scorrimento orizzontale con testo al 200 % in ${path}`).toBeLessThanOrEqual(
0,
);
}
});
test('reflow a 320 px: nessuno scorrimento orizzontale in tutte le pagine', async ({ page }) => {
await page.setViewportSize({ width: 320, height: 640 });
for (const path of ALL_PAGES) {
await page.goto(path);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow, `scorrimento orizzontale a 320 px in ${path}`).toBeLessThanOrEqual(0);
}
});
test('preferenza «riduci movimento»: nessuna transizione', async ({ browser }) => {
const context = await browser.newContext({ reducedMotion: 'reduce' });
const page = await context.newPage();
await page.goto('/');
const duration = await page
.locator('.card')
.first()
.evaluate((el) => getComputedStyle(el).transitionDuration);
expect(
duration.split(',').every((d) => parseFloat(d) <= 0.001),
`durata transizioni con movimento ridotto: ${duration}`,
).toBe(true);
await context.close();
});
+103
View File
@@ -0,0 +1,103 @@
/**
* Modulo di contatto (brief §10.1, §11.4). Con `contactForm.mode = 'off'` (predefinito) si
* verifica la card «Scrivici una e-mail»; con il modulo attivo (CONTACT_FORM_MODE=php o
* endpoint nella build) si verificano validazione, honeypot, tempo minimo e pagina di conferma.
*/
import { expect, test } from '@playwright/test';
test('contatti: modulo oppure card e-mail, a seconda della configurazione', async ({ page }) => {
await page.goto('/contatti/');
const forms = await page.locator('form[data-contact-form]').count();
if (forms === 0) {
const card = page.locator('[data-contact-mode="off"]');
await expect(card).toBeVisible();
await expect(card.getByRole('heading', { name: 'Scrivici una e-mail' })).toBeVisible();
const href = await card.locator('a[href^="mailto:"]').getAttribute('href');
expect(href).toBe(
`mailto:info@studiograssoezio.it?subject=${encodeURIComponent('Richiesta di informazioni dal sito')}`,
);
} else {
await expect(page.locator('form[data-contact-form]')).toBeVisible();
}
});
test.describe('modulo attivo', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/contatti/');
const forms = await page.locator('form[data-contact-form]').count();
test.skip(forms === 0, 'modulo disattivato (contactForm.mode = "off")');
});
test('campi obbligatori, etichette e informativa', async ({ page }) => {
const form = page.locator('form[data-contact-form]');
for (const label of [
'Nome e cognome',
'E-mail',
'Telefono / Cellulare',
'Oggetto',
'Messaggio',
]) {
const field = form.getByLabel(label);
await expect(field, `campo «${label}»`).toBeVisible();
await expect(field, `campo «${label}» obbligatorio`).toHaveAttribute('required', '');
}
const consent = form.locator('input[name="privacy"]');
await expect(consent).toHaveAttribute('required', '');
await expect(form.locator('label[for="cf-privacy"] a')).toHaveAttribute(
'href',
'/privacy-policy/',
);
await expect(form).toContainText('* campo obbligatorio');
});
test('honeypot nascosto e campo ts valorizzato', async ({ page }) => {
const trap = page.locator('input[name="sito_web"]');
await expect(trap).toHaveAttribute('tabindex', '-1');
await expect(trap).not.toBeInViewport();
await expect(page.locator('.contact-form__trap')).toHaveAttribute('aria-hidden', 'true');
const ts = await page.locator('input[name="ts"]').inputValue();
expect(Number(ts), 'timestamp di apertura della pagina').toBeGreaterThan(1_600_000_000_000);
});
test('invio vuoto: errori in italiano accanto ai campi e riepilogo', async ({ page }) => {
await page.getByRole('button', { name: /Invia la richiesta/ }).click();
const summary = page.locator('[data-form-summary]');
await expect(summary).toBeVisible();
await expect(summary).toBeFocused();
await expect(summary).toContainText('Controlla i campi evidenziati');
await expect(page.locator('#cf-nome')).toHaveAttribute('aria-invalid', 'true');
await expect(page.locator('#cf-nome-err')).toHaveText('Compila questo campo.');
await expect(page.locator('#cf-privacy-err')).toContainText('informativa sulla privacy');
await expect(page).toHaveURL('/contatti/');
});
test('e-mail non valida', async ({ page }) => {
await page.locator('#cf-email').fill('non-valida');
await page.locator('#cf-email').blur();
await expect(page.locator('#cf-email-err')).toContainText('indirizzo e-mail valido');
});
test('invio troppo rapido bloccato, poi invio e pagina di conferma', async ({ page }) => {
await page.route('**/contact.php', (route) =>
route.fulfill({ status: 303, headers: { Location: '/contatti/grazie/' } }),
);
await page.locator('#cf-nome').fill('Mario Rossi');
await page.locator('#cf-email').fill('mario.rossi@example.com');
await page.locator('#cf-telefono').fill('+39 0141 000000');
await page.locator('#cf-oggetto').fill('Richiesta di preventivo');
await page
.locator('#cf-messaggio')
.fill('Vorrei un preventivo per la tenuta della contabilità.');
await page.locator('#cf-privacy').check();
// primo invio entro 3 secondi dall'apertura della pagina: bloccato dall'anti-spam
await page.getByRole('button', { name: /Invia la richiesta/ }).click();
await expect(page.locator('[data-form-status]')).toHaveText(/Attendi qualche secondo/);
await expect(page).toHaveURL('/contatti/');
await page.waitForTimeout(3_200);
await page.getByRole('button', { name: /Invia la richiesta/ }).click();
await expect(page).toHaveURL('/contatti/grazie/');
await expect(page.locator('h1')).toHaveText('Richiesta inviata');
});
});
+67
View File
@@ -0,0 +1,67 @@
/**
* Menu mobile a 390 px (brief §5.2): apertura e chiusura, aria-expanded, Esc, focus, sottomenu.
*/
import { expect, test } from '@playwright/test';
import { SERVICE_PAGES } from '../helpers/site';
test.use({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
test('il menu mobile si apre e si chiude', async ({ page }) => {
await page.goto('/');
const toggle = page.locator('[data-menu-open]');
const menu = page.locator('#menu-mobile');
await expect(page.getByRole('navigation', { name: 'Principale' })).toBeHidden();
await expect(toggle).toBeVisible();
await expect(toggle).toHaveAttribute('aria-controls', 'menu-mobile');
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(menu).toBeHidden();
await toggle.click();
await expect(menu).toBeVisible();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(page.locator('[data-menu-close]')).toBeFocused();
for (const label of ['Lo studio', 'Servizi', 'Contatti', 'Dove siamo', 'Link utili']) {
await expect(menu.getByRole('link', { name: label, exact: true })).toBeVisible();
}
await expect(menu.locator('a[href^="tel:"]')).toBeVisible();
await page.locator('[data-menu-close]').click();
await expect(menu).toBeHidden();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(toggle).toBeFocused();
});
test('il menu mobile si chiude con Esc', async ({ page }) => {
await page.goto('/');
const toggle = page.locator('[data-menu-open]');
await toggle.click();
await expect(page.locator('#menu-mobile')).toBeVisible();
await page.keyboard.press('Escape');
await expect(page.locator('#menu-mobile')).toBeHidden();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(toggle).toBeFocused();
});
test('il sottomenu dei servizi nel menu mobile', async ({ page }) => {
await page.goto('/');
await page.locator('[data-menu-open]').click();
const subToggle = page.locator('#menu-mobile [data-submenu-toggle]');
const sub = page.locator('#menu-mobile-servizi');
await expect(sub).toBeHidden();
await subToggle.click();
await expect(subToggle).toHaveAttribute('aria-expanded', 'true');
await expect(sub).toBeVisible();
await expect(sub.getByRole('link')).toHaveCount(SERVICE_PAGES.length);
await sub.getByRole('link').nth(2).click();
await expect(page).toHaveURL(/\/servizi\/[a-z-]+\/$/);
await expect(page.locator('#menu-mobile')).toBeHidden();
});
test('a 390 px non c’è scorrimento orizzontale', async ({ page }) => {
await page.goto('/');
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow, 'larghezza in eccesso della home a 390 px').toBeLessThanOrEqual(0);
});
+139
View File
@@ -0,0 +1,139 @@
/**
* Navigazione (brief §5.2, §5.3, §11.4): intestazione, sottomenu dei servizi, footer,
* breadcrumb, precedente/successivo e redirect delle ancore del vecchio sito.
*/
import { expect, test } from '@playwright/test';
import { SERVICE_PAGES } from '../helpers/site';
const MAIN_NAV = [
{ label: 'Lo studio', path: '/studio/' },
{ label: 'Servizi', path: '/servizi/' },
{ label: 'Contatti', path: '/contatti/' },
{ label: 'Dove siamo', path: '/dove-siamo/' },
{ label: 'Link utili', path: '/link-utili/' },
];
test('le voci dell’intestazione portano alle pagine giuste', async ({ page }) => {
for (const item of MAIN_NAV) {
await page.goto('/');
const nav = page.getByRole('navigation', { name: 'Principale' });
await nav.getByRole('link', { name: item.label, exact: true }).click();
await expect(page, `la voce «${item.label}» porta a ${item.path}`).toHaveURL(item.path);
await expect(
page.getByRole('navigation', { name: 'Principale' }).getByRole('link', {
name: item.label,
exact: true,
}),
`la voce «${item.label}» è evidenziata come pagina corrente`,
).toHaveAttribute('aria-current', 'page');
}
});
test('logo e pulsante «Richiedi un preventivo»', async ({ page }) => {
await page.goto('/studio/');
await page.locator('header .brand').first().click();
await expect(page).toHaveURL('/');
await page
.getByRole('navigation', { name: 'Principale' })
.getByRole('link', { name: 'Richiedi un preventivo' })
.click();
await expect(page).toHaveURL('/contatti/');
});
test('il sottomenu «Servizi» elenca i 6 servizi e si apre con il pulsante', async ({ page }) => {
await page.goto('/');
const toggle = page.locator('.nav [data-submenu-toggle]');
const submenu = page.locator('#sottomenu-servizi');
await expect(submenu).toBeHidden();
await toggle.click();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(submenu).toBeVisible();
await expect(submenu.getByRole('link')).toHaveCount(SERVICE_PAGES.length);
await submenu.getByRole('link').first().click();
await expect(page).toHaveURL(/\/servizi\/[a-z-]+\/$/);
await expect(
page.getByRole('navigation', { name: 'Principale' }).getByRole('link', {
name: 'Servizi',
exact: true,
}),
).toHaveAttribute('aria-current', 'true');
});
test('il sottomenu si apre anche al passaggio del mouse e si chiude con un clic fuori', async ({
page,
}) => {
await page.goto('/');
const submenu = page.locator('#sottomenu-servizi');
await page.locator('.nav__item--has-sub').hover();
await expect(submenu).toBeVisible();
await page.mouse.move(10, 600);
await expect(submenu).toBeHidden();
await page.locator('.nav [data-submenu-toggle]').click();
await expect(submenu).toBeVisible();
await page.mouse.move(10, 600);
await page.locator('main h1').click();
await expect(submenu).toBeHidden();
});
test('tutti i link del footer funzionano', async ({ page, request }) => {
await page.goto('/');
const hrefs = await page
.locator('footer a[href^="/"]')
.evaluateAll((links) => links.map((a) => a.getAttribute('href') ?? ''));
expect(hrefs.length, 'link interni nel footer').toBeGreaterThanOrEqual(11);
for (const href of new Set(hrefs)) {
const response = await request.get(href);
expect(response.status(), `link del footer ${href}`).toBe(200);
}
for (const label of ['Privacy policy', 'Cookie policy', 'Note legali', 'Accessibilità']) {
await expect(
page.getByRole('navigation', { name: 'Informazioni legali' }).getByRole('link', {
name: label,
}),
).toBeVisible();
}
});
test('breadcrumb, barra laterale e precedente/successivo nelle pagine dei servizi', async ({
page,
}) => {
for (const path of SERVICE_PAGES) {
await page.goto(path);
const breadcrumb = page.getByRole('navigation', { name: 'Percorso' });
await expect(breadcrumb.getByRole('link', { name: 'Home' })).toHaveAttribute('href', '/');
await expect(breadcrumb.getByRole('link', { name: 'Servizi' })).toHaveAttribute(
'href',
'/servizi/',
);
await expect(
page.locator('.sidenav a[aria-current="page"]'),
`servizio corrente evidenziato in ${path}`,
).toHaveAttribute('href', path);
}
await page.goto(SERVICE_PAGES[0]);
const pager = page.getByRole('navigation', { name: 'Servizio precedente e successivo' });
const next = await pager.locator('a[rel="next"]').getAttribute('href');
await pager.locator('a[rel="next"]').click();
await expect(page).toHaveURL(next ?? '');
await page
.getByRole('navigation', { name: 'Servizio precedente e successivo' })
.locator('a[rel="prev"]')
.click();
await expect(page).toHaveURL(SERVICE_PAGES[0]);
});
test('le ancore del vecchio sito portano al servizio corrispondente', async ({ page }) => {
await page.goto('/servizi/');
const cards = await page
.locator('[data-legacy-href]')
.evaluateAll((els) =>
els.map((el) => ({ id: el.id, href: el.getAttribute('data-legacy-href') })),
);
expect(cards.length, 'card con ancora del vecchio sito').toBe(6);
for (const { id, href } of cards) {
await page.goto(`/servizi/#${id}`);
await expect(page, `l'ancora #${id} porta a ${href}`).toHaveURL(href ?? '');
}
await page.goto('/servizi/#ancora-sconosciuta');
await expect(page).toHaveURL('/servizi/#ancora-sconosciuta');
});
+99
View File
@@ -0,0 +1,99 @@
/**
* Privacy (brief §8.2, §11.4): nessuna richiesta verso host esterni al caricamento delle pagine,
* nessun cookie, localStorage vuoto, mappa Google caricata solo dopo il clic.
*/
import { expect, test } from '@playwright/test';
import { ALL_PAGES, isLocalRequest, stubGoogle } from '../helpers/site';
test('nessuna richiesta verso host esterni, nessun cookie e localStorage vuoto', async ({
page,
context,
}) => {
const external: string[] = [];
page.on('request', (req) => {
if (!isLocalRequest(req.url())) external.push(`${req.url()} (pagina ${page.url()})`);
});
for (const path of ALL_PAGES) {
await page.goto(path, { waitUntil: 'networkidle' });
// scorrimento fino in fondo: eventuali contenuti caricati in modo differito partono ora
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForLoadState('networkidle');
const storage = await page.evaluate(() => window.localStorage.length);
expect(storage, `voci in localStorage dopo ${path}`).toBe(0);
}
expect(external, 'richieste verso host diversi da localhost').toEqual([]);
expect(await context.cookies(), 'cookie impostati durante la navigazione').toEqual([]);
});
for (const path of ['/', '/contatti/', '/dove-siamo/']) {
test(`mappa click-to-load in ${path}`, async ({ page, context }) => {
const google = await stubGoogle(page);
await page.goto(path, { waitUntil: 'networkidle' });
await expect(page.locator('iframe'), 'iframe presenti prima del clic').toHaveCount(0);
expect(google, 'richieste a Google prima del clic').toEqual([]);
const blocks = page.locator('[data-map-consent]');
const count = await blocks.count();
expect(count, 'blocchi mappa nella pagina').toBeGreaterThan(0);
const first = blocks.first();
await expect(first).toContainText('Google Maps');
await expect(first.locator('a[href="/cookie-policy/"]')).toHaveCount(1);
await expect(first.locator('a[href^="https://www.google.com/maps/search/"]')).toHaveCount(1);
await expect(first.locator('a[href^="https://www.openstreetmap.org/search"]')).toHaveCount(1);
await first.locator('[data-map-load]').click();
const iframe = first.locator('iframe');
await expect(iframe).toHaveCount(1);
await expect(iframe).toHaveAttribute('src', /^https:\/\/www\.google\.com\/maps\/embed\?pb=/);
await expect(iframe).toHaveAttribute('title', /Mappa/);
await expect(iframe).toHaveAttribute('loading', 'lazy');
await expect
.poll(() => google.length, { message: 'richiesta a Google dopo il clic' })
.toBeGreaterThan(0);
const remembered = await page.evaluate(() => sessionStorage.getItem('mappa-consentita'));
expect(remembered, 'scelta ricordata in sessionStorage').toBe('1');
// la scelta vale per la sessione: ricaricando, le mappe compaiono senza un nuovo clic
await page.reload({ waitUntil: 'networkidle' });
await expect(page.locator('[data-map-consent] iframe')).toHaveCount(count);
const ours = (await context.cookies()).filter((c) => !c.domain.includes('google'));
expect(ours, 'cookie del sito dopo il caricamento della mappa').toEqual([]);
});
}
test('senza JavaScript restano i link esterni della mappa e la navigazione', async ({
browser,
}) => {
const context = await browser.newContext({ javaScriptEnabled: false });
const page = await context.newPage();
await page.goto('/dove-siamo/');
await expect(page.locator('[data-map-load]').first()).toBeHidden();
await expect(
page.locator('a[href^="https://www.google.com/maps/search/"]').first(),
).toBeVisible();
await expect(page.locator('iframe')).toHaveCount(0);
await page.goto('/');
await expect(
page.getByRole('navigation', { name: 'Principale' }).getByRole('link', { name: 'Lo studio' }),
).toBeVisible();
await context.close();
});
test('senza JavaScript il menu è navigabile anche su mobile', async ({ browser }) => {
const context = await browser.newContext({
javaScriptEnabled: false,
viewport: { width: 390, height: 844 },
});
const page = await context.newPage();
await page.goto('/');
await expect(page.locator('[data-menu-open]')).toBeHidden();
const menu = page.getByRole('navigation', { name: 'Menu mobile' });
await expect(menu.getByRole('link', { name: 'Contatti', exact: true })).toBeVisible();
await expect(menu.locator('#menu-mobile-servizi a').first()).toBeVisible();
await context.close();
});
+70
View File
@@ -0,0 +1,70 @@
/**
* Smoke test di tutte le pagine (brief §11.4): risposta 200, un solo <h1>, lang="it",
* titolo e descrizione presenti e unici, canonical corretto, nessun errore in console.
*/
import { expect, test } from '@playwright/test';
import { ALL_PAGES, SITE, collectConsoleErrors } from '../helpers/site';
for (const path of ALL_PAGES) {
test(`pagina ${path}: struttura e metadati`, async ({ page }) => {
const errors = collectConsoleErrors(page);
const response = await page.goto(path);
expect(response?.status(), `stato HTTP della pagina ${path}`).toBe(200);
await expect(page.locator('html'), `lang della pagina ${path}`).toHaveAttribute('lang', 'it');
await expect(page.locator('h1'), `numero di <h1> nella pagina ${path}`).toHaveCount(1);
await expect(page.locator('h1'), `<h1> visibile nella pagina ${path}`).toBeVisible();
const title = await page.title();
expect(title.length, `titolo della pagina ${path}`).toBeGreaterThan(10);
const description = await page.locator('meta[name="description"]').getAttribute('content');
expect(
description?.length ?? 0,
`meta description della pagina ${path}`,
).toBeGreaterThanOrEqual(120);
if (path !== '/404.html') {
await expect(
page.locator('link[rel="canonical"]'),
`canonical della pagina ${path}`,
).toHaveAttribute('href', `${SITE}${path}`);
}
await expect(page.locator('footer'), `P.IVA nel footer della pagina ${path}`).toContainText(
'P.IVA 01597790052',
);
expect(errors, `errori nella console della pagina ${path}`).toEqual([]);
});
}
test('titoli e descrizioni sono unici su tutto il sito', async ({ page }) => {
const titles = new Map<string, string>();
const descriptions = new Map<string, string>();
for (const path of ALL_PAGES) {
await page.goto(path);
const title = await page.title();
const description =
(await page.locator('meta[name="description"]').getAttribute('content')) ?? '';
expect(titles.get(title), `titolo «${title}» di ${path} già usato`).toBeUndefined();
expect(descriptions.get(description), `descrizione di ${path} già usata`).toBeUndefined();
titles.set(title, path);
descriptions.set(description, path);
}
});
test('un indirizzo inesistente mostra la pagina 404 personalizzata', async ({ page }) => {
const response = await page.goto('/pagina-che-non-esiste/');
expect(response?.status(), 'stato HTTP di un indirizzo inesistente').toBe(404);
await expect(page.locator('h1')).toHaveText('Pagina non trovata');
const main = page.locator('main');
for (const href of ['/', '/servizi/', '/contatti/']) {
await expect(main.locator(`a[href="${href}"]`), `link a ${href} nella 404`).toHaveCount(1);
}
await expect(page.locator('meta[name="robots"]')).toHaveAttribute('content', /noindex/);
});
test('la pagina di conferma del modulo è noindex', async ({ page }) => {
await page.goto('/contatti/grazie/');
await expect(page.locator('h1')).toHaveText('Richiesta inviata');
await expect(page.locator('meta[name="robots"]')).toHaveAttribute('content', /noindex/);
});
+67
View File
@@ -0,0 +1,67 @@
/**
* Supporto ai test: elenco delle pagine letto dalla sitemap generata in dist/ (nessuna lista da
* tenere allineata a mano), URL del sito e utilità comuni.
*/
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { Page } from '@playwright/test';
export const SITE = (process.env.SITE_URL || 'https://www.grassoezio.it').replace(/\/+$/, '');
const DIST = resolve(import.meta.dirname, '..', '..', 'dist');
function locs(xml: string): string[] {
return [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1].trim());
}
/** Percorsi delle pagine elencate nella sitemap (es. «/», «/studio/»). */
export function sitemapPaths(): string[] {
const index = resolve(DIST, 'sitemap-index.xml');
if (!existsSync(index)) {
throw new Error('Sitemap non trovata in dist/: eseguire `npm run build` prima dei test.');
}
const paths: string[] = [];
for (const sitemap of locs(readFileSync(index, 'utf8'))) {
const file = resolve(DIST, new URL(sitemap).pathname.replace(/^\//, ''));
for (const url of locs(readFileSync(file, 'utf8'))) paths.push(new URL(url).pathname);
}
return [...new Set(paths)].sort();
}
/** Pagine generate ma escluse dalla sitemap (noindex). */
export const EXTRA_PAGES = ['/404.html', '/contatti/grazie/'];
export const PAGES = sitemapPaths();
export const ALL_PAGES = [...PAGES, ...EXTRA_PAGES];
export const SERVICE_PAGES = PAGES.filter((p) => /^\/servizi\/[^/]+\/$/.test(p));
/** Vero per le richieste che restano sul server locale di test. */
export function isLocalRequest(url: string): boolean {
const u = new URL(url);
if (u.protocol === 'data:' || u.protocol === 'blob:' || u.protocol === 'about:') return true;
return u.hostname === '127.0.0.1' || u.hostname === 'localhost';
}
/** Raccoglie errori della console e della pagina. */
export function collectConsoleErrors(page: Page): string[] {
const errors: string[] = [];
page.on('console', (msg) => {
if (msg.type() === 'error') errors.push(msg.text());
});
page.on('pageerror', (err) => errors.push(err.message));
return errors;
}
/** Risposta finta per Google Maps: nei test nessuna richiesta esce dalla macchina. */
export async function stubGoogle(page: Page): Promise<string[]> {
const requested: string[] = [];
await page.route('https://www.google.com/**', (route) => {
requested.push(route.request().url());
return route.fulfill({
status: 200,
contentType: 'text/html',
body: '<!doctype html><title>Mappa</title>',
});
});
return requested;
}