Files
jobtrackingapp/job-tracker-ui/e2e/rules-draft-repair.spec.ts

252 lines
16 KiB
TypeScript

import AxeBuilder from '@axe-core/playwright';
import { expect, test as base, type APIRequestContext, type Page, type TestInfo } from '@playwright/test';
import { translations } from '../src/i18n/translations';
const apiUrl = 'http://localhost:5302/api';
const password = 'E2ePassword123!';
const baseline = { id: 1, appliedFollowUpDays: 14, appliedGhostDays: 30, offerFollowUpDays: 7, offerGhostDays: 14, feedbackFollowUpDays: 7, feedbackGhostDays: 14 };
async function createAccount(admin: APIRequestContext, headers: Record<string, string>) {
const email = `rules-repair-${Date.now()}-${Math.random().toString(36).slice(2)}@example.test`;
expect((await admin.post(`${apiUrl}/users`, { headers, data: { email, password, roles: [] } })).status()).toBe(200);
return email;
}
async function login(api: APIRequestContext, email: string) {
expect((await api.post(`${apiUrl}/auth/login`, { data: { email, password } })).status()).toBe(200);
const me = await (await api.get(`${apiUrl}/auth/me`)).json();
const csrf = (await api.storageState()).cookies.find(cookie => cookie.name === 'XSRF-TOKEN')!.value;
return { 'X-CSRF-TOKEN': csrf, 'X-Session-Context': me.sessionContext as string };
}
const test = base.extend<{ headers: Record<string, string> }>({
headers: async ({ playwright, page, context }, provide) => {
const admin = await playwright.request.newContext();
try {
const adminHeaders = await login(admin, 'e2e@example.test');
const email = await createAccount(admin, adminHeaders);
await context.addInitScript(() => { if (!localStorage.getItem('uiLanguage')) localStorage.setItem('uiLanguage', 'en'); });
await context.route('**/*', route => {
const url = new URL(route.request().url());
return ['localhost', '127.0.0.1'].includes(url.hostname) || ['data:', 'blob:', 'about:'].includes(url.protocol)
? route.continue() : route.abort();
});
await provide(await login(page.request, email));
} finally { await admin.dispose(); }
},
});
async function choose(page: Page, label: string) {
if (page.viewportSize()!.width < 768) {
const selector = page.getByRole('combobox', { name: /Settings section|Innstillingsområde/ });
await selector.focus();
await selector.press('Enter');
await page.getByRole('option', { name: label, exact: true }).focus();
await page.keyboard.press('Enter');
await expect(selector).toBeFocused();
} else {
const tab = page.getByRole('tab', { name: label, exact: true });
await tab.focus();
await tab.press('Enter');
await expect(tab).toHaveAttribute('aria-selected', 'true');
}
}
async function capture(page: Page, info: TestInfo, name: string) {
const outside = await page.getByRole('main').evaluate(main => Array.from(main.querySelectorAll('input,button,p,h2,[role="status"]'))
.filter(node => node.getClientRects().length && getComputedStyle(node).visibility !== 'hidden')
.filter(node => { const rect = node.getBoundingClientRect(); return rect.left < -1 || rect.right > innerWidth + 1; })
.map(node => node.textContent?.slice(0, 80)));
expect(outside, `${name} usable controls/reflow`).toEqual([]);
const path = info.outputPath(`${name}.png`);
await page.screenshot({ path, fullPage: true, animations: 'disabled' });
await info.attach(name, { path, contentType: 'image/png' });
const result = await new AxeBuilder({ page }).withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']).analyze();
await info.attach(`${name}-axe`, { body: JSON.stringify({ violations: result.violations, incomplete: result.incomplete }), contentType: 'application/json' });
expect(result.violations).toEqual([]);
}
function response(page: Page, method: string) {
return page.waitForResponse(r => r.url() === `${apiUrl}/rules` && r.request().method() === method);
}
test('[P5-15-01R-02 PRES-S03 W11] unsaved Rules draft survives an internal tab round trip without saving', async ({ page, headers }, info) => {
expect((await page.request.put(`${apiUrl}/rules`, { headers, data: {
id: 1, appliedFollowUpDays: 14, appliedGhostDays: 30,
offerFollowUpDays: 7, offerGhostDays: 14, feedbackFollowUpDays: 7, feedbackGhostDays: 14,
} })).status()).toBe(204);
let writes = 0;
page.on('request', request => { if (new URL(request.url()).pathname === '/api/rules' && request.method() === 'PUT') writes++; });
await page.goto('/settings');
await page.getByRole('tab', { name: 'Follow-ups', exact: true }).click();
const field = page.getByRole('spinbutton', { name: 'Applied: follow-up days', exact: true });
await expect(field).toHaveValue('14');
await field.fill('5');
await expect(field).toHaveValue('5');
await page.getByRole('tab', { name: 'Notifications', exact: true }).click();
await expect(page.getByLabel('Email reminders for follow-ups', { exact: true })).toBeVisible();
await page.getByRole('tab', { name: 'Follow-ups', exact: true }).click();
await expect(field).toBeVisible();
const persisted = await (await page.request.get(`${apiUrl}/rules`)).json();
await info.attach('rules-draft-tab-round-trip', { body: JSON.stringify({
initial: 14, entered: 5, afterReturn: await field.inputValue(), persisted: persisted.appliedFollowUpDays, writes,
}), contentType: 'application/json' });
expect(writes).toBe(0);
expect(persisted.appliedFollowUpDays).toBe(14);
await expect(field).toHaveValue('5');
});
test('[P5-15-01R-02] native Rules save, validation, failure/retry and discard across themes/locales/viewports', async ({ page, headers }, info) => {
test.setTimeout(180_000);
await page.emulateMedia({ reducedMotion: 'reduce' });
for (const variant of [
{ language: 'en', mode: 'light', width: 1440 }, { language: 'nb', mode: 'dark', width: 768 },
{ language: 'en', mode: 'dark', width: 390 }, { language: 'nb', mode: 'light', width: 320 },
] as const) {
const t = translations[variant.language];
const suffix = `${variant.language}-${variant.mode}-${variant.width}`;
expect((await page.request.put(`${apiUrl}/rules`, { headers, data: baseline })).status()).toBe(204);
expect((await page.request.put(`${apiUrl}/auth/preferences/language`, { headers, data: { language: variant.language === 'nb' ? 'nb-NO' : 'en' } })).status()).toBe(204);
await page.setViewportSize({ width: variant.width, height: 900 });
await page.goto('/settings');
await page.evaluate(({ mode, language }) => { localStorage.setItem('jobtracker.themeMode', mode); localStorage.setItem('uiLanguage', language); }, variant);
await page.reload();
await expect(page.locator('html')).toHaveAttribute('data-color-scheme', variant.mode);
await choose(page, t.settingsTabFollowUps);
const main = page.getByRole('main');
const labels = [t.rulesAppliedFollowUpDays, t.rulesAppliedGhostDays, t.rulesOfferFollowUpDays, t.rulesOfferGhostDays, t.rulesFeedbackFollowUpDays, t.rulesFeedbackGhostDays];
const fields = labels.map(name => main.getByRole('spinbutton', { name, exact: true }));
await expect(fields[0]).toHaveValue('14');
for (const [index, value] of ['5', '40', '9', '20', '11', '25'].entries()) await fields[index].fill(value);
for (let i = 0; i < 2; i++) {
await choose(page, t.settingsTabNotifications);
await expect(main.getByRole('status')).toContainText(t.assetsUnsavedChanges);
await choose(page, t.settingsTabFollowUps);
}
for (const [index, value] of ['5', '40', '9', '20', '11', '25'].entries()) await expect(fields[index]).toHaveValue(value);
expect(await (await page.request.get(`${apiUrl}/rules`)).json()).toEqual(baseline);
await capture(page, info, `rules-draft-${suffix}`);
await fields[0].fill('');
await fields[2].fill('366');
let writes = 0;
const countWrite = (request: import('@playwright/test').Request) => { if (request.url() === `${apiUrl}/rules` && request.method() === 'PUT') writes++; };
page.on('request', countWrite);
await main.getByRole('button', { name: t.rulesSave, exact: true }).press('Enter');
await expect(fields[0]).toHaveAttribute('aria-invalid', 'true');
await expect(fields[0]).toHaveAccessibleDescription(t.rulesDaysInvalid);
await choose(page, t.settingsTabNotifications);
await choose(page, t.settingsTabFollowUps);
await expect(fields[0]).toHaveValue('');
await expect(fields[2]).toHaveValue('366');
await expect(fields[2]).toHaveAccessibleDescription(t.rulesDaysInvalid);
expect(writes).toBe(0);
await capture(page, info, `rules-validation-${suffix}`);
await fields[0].fill('5'); await fields[2].fill('9');
let fail = true;
await page.route(`${apiUrl}/rules`, route => {
if (route.request().method() === 'PUT' && fail) { fail = false; return route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ message: 'Synthetic internal details must not appear' }) }); }
return route.continue();
});
const failed = response(page, 'PUT');
await main.getByRole('button', { name: t.rulesSave, exact: true }).press('Enter');
expect((await failed).status()).toBe(500);
await expect(main.getByRole('alert')).toHaveText(t.rulesSaveFailed);
await choose(page, t.settingsTabNotifications); await choose(page, t.settingsTabFollowUps);
await expect(main.getByRole('alert')).toHaveText(t.rulesSaveFailed);
await expect(fields[0]).toHaveValue('5');
expect(await (await page.request.get(`${apiUrl}/rules`)).json()).toEqual(baseline);
await capture(page, info, `rules-save-error-${suffix}`);
const retried = response(page, 'PUT');
await main.getByRole('button', { name: t.rulesSave, exact: true }).press('Enter');
expect((await retried).status()).toBe(204);
await expect(main.getByRole('status')).toHaveCount(0);
await expect(main.getByRole('alert')).toHaveCount(0);
const saved = { id: 1, appliedFollowUpDays: 5, appliedGhostDays: 40, offerFollowUpDays: 9, offerGhostDays: 20, feedbackFollowUpDays: 11, feedbackGhostDays: 25 };
expect(await (await page.request.get(`${apiUrl}/rules`)).json()).toEqual(saved);
expect(writes).toBe(2);
page.off('request', countWrite);
await page.unroute(`${apiUrl}/rules`);
await page.reload(); await choose(page, t.settingsTabFollowUps);
await expect(fields[0]).toHaveValue('5'); await expect(fields[2]).toHaveValue('9');
await fields[0].fill('6'); await fields[2].fill('10');
await choose(page, t.settingsTabNotifications); await choose(page, t.settingsTabFollowUps);
await main.getByRole('button', { name: t.assetsDiscardChanges, exact: true }).press('Enter');
await expect(fields[0]).toHaveValue('5'); await expect(fields[2]).toHaveValue('9');
await expect(main.getByRole('status')).toHaveCount(0);
expect(await (await page.request.get(`${apiUrl}/rules`)).json()).toEqual(saved);
await capture(page, info, `rules-discard-${suffix}`);
}
});
test('[P5-15-01R-02] delayed native Rules reads and save completion do not reset a newer session draft', async ({ page, headers }, info) => {
expect((await page.request.put(`${apiUrl}/rules`, { headers, data: baseline })).status()).toBe(204);
let releaseRead!: () => void;
const readGate = new Promise<void>(resolve => { releaseRead = resolve; });
let reads = 0;
await page.route(`${apiUrl}/rules`, async route => {
if (route.request().method() === 'GET') { reads++; await readGate; }
await route.continue();
});
await page.goto('/settings'); await choose(page, translations.en.settingsTabFollowUps);
await expect(page.getByRole('status')).toHaveText(translations.en.rulesLoading);
await choose(page, translations.en.settingsTabNotifications); await choose(page, translations.en.settingsTabFollowUps);
releaseRead();
const field = page.getByRole('spinbutton', { name: translations.en.rulesAppliedFollowUpDays, exact: true });
await expect(field).toHaveValue('14');
expect(reads).toBe(1);
await page.unroute(`${apiUrl}/rules`);
await field.fill('5');
let releaseSave!: () => void;
const saveGate = new Promise<void>(resolve => { releaseSave = resolve; });
await page.route(`${apiUrl}/rules`, async route => { if (route.request().method() === 'PUT') await saveGate; await route.continue(); });
const savedResponse = response(page, 'PUT');
await page.getByRole('button', { name: translations.en.rulesSave, exact: true }).click();
await expect(page.getByRole('button', { name: translations.en.rulesSaving, exact: true })).toBeDisabled();
await field.fill('6');
await choose(page, translations.en.settingsTabNotifications); await choose(page, translations.en.settingsTabFollowUps);
releaseSave();
expect((await savedResponse).status()).toBe(204);
await expect(field).toHaveValue('6');
await expect(page.getByRole('main').getByRole('status')).toContainText(translations.en.assetsUnsavedChanges);
expect((await (await page.request.get(`${apiUrl}/rules`)).json()).appliedFollowUpDays).toBe(5);
await info.attach('native-save-snapshot', { body: JSON.stringify({ initial: 14, submitted: 5, newerDraft: 6, persisted: 5, reads }), contentType: 'application/json' });
await page.getByRole('button', { name: translations.en.assetsDiscardChanges, exact: true }).click();
await expect(field).toHaveValue('5');
await field.fill('8');
await expect(page.getByRole('main').getByRole('status')).toContainText(translations.en.rulesDraftScope);
await page.getByRole('button', { name: translations.en.jobApplications, exact: true }).click();
await page.getByRole('navigation', { name: translations.en.navigation, exact: true }).getByRole('button', { name: translations.en.settings, exact: true }).click();
await choose(page, translations.en.settingsTabFollowUps);
await expect(field).toHaveValue('5');
});
test('[P5-15-01R-02 PRES-E09] Rules API ignores forged owners and account switching disposes the previous draft', async ({ page, playwright, headers }, info) => {
const meA = await (await page.request.get(`${apiUrl}/auth/me`)).json();
const ownerA = await playwright.request.newContext({ storageState: await page.context().storageState() });
const admin = await playwright.request.newContext();
const anonymous = await playwright.request.newContext();
try {
const adminHeaders = await login(admin, 'e2e@example.test');
const emailB = await createAccount(admin, adminHeaders);
expect((await page.request.put(`${apiUrl}/rules`, { headers, data: baseline })).status()).toBe(204);
await page.goto('/settings'); await choose(page, translations.en.settingsTabFollowUps);
const field = page.getByRole('spinbutton', { name: translations.en.rulesAppliedFollowUpDays, exact: true });
await expect(field).toHaveValue('14'); await field.fill('9');
const headersB = await login(page.request, emailB);
expect((await page.request.put(`${apiUrl}/rules?ownerUserId=${meA.id}`, { headers: headersB, data: { ...baseline, id: 999, ownerUserId: meA.id, appliedFollowUpDays: 22 } })).status()).toBe(204);
expect((await (await page.request.get(`${apiUrl}/rules?ownerUserId=${meA.id}`)).json()).appliedFollowUpDays).toBe(22);
expect((await (await ownerA.get(`${apiUrl}/rules`)).json()).appliedFollowUpDays).toBe(14);
await expect(page).toHaveURL(/\/login\?sessionChanged=1$/);
await expect(page.getByText(translations.en.sessionChangedCleared, { exact: true })).toBeVisible();
await expect(field).toHaveCount(0);
await page.goto('/settings'); await choose(page, translations.en.settingsTabFollowUps);
await expect(field).toHaveValue('22');
await expect(page.getByRole('main').getByRole('status')).toHaveCount(0);
expect((await anonymous.get(`${apiUrl}/rules`)).status()).toBe(401);
expect((await anonymous.put(`${apiUrl}/rules`, { data: baseline })).status()).toBe(401);
await info.attach('rules-native-account-boundary', { body: JSON.stringify({ accountAUnchanged: 14, accountB: 22, oldDraft: 9, oldPageDisposed: true, anonymous: [401, 401] }), contentType: 'application/json' });
} finally { await ownerA.dispose(); await admin.dispose(); await anonymous.dispose(); }
});