79 lines
2.3 KiB
TypeScript
79 lines
2.3 KiB
TypeScript
import { test as base, expect, type Page } from '@playwright/test';
|
|
|
|
export interface ConsoleIssue {
|
|
kind: 'console.error' | 'pageerror';
|
|
text: string;
|
|
}
|
|
|
|
interface GuardState {
|
|
issues: ConsoleIssue[];
|
|
allowed: RegExp[];
|
|
}
|
|
|
|
const guards = new WeakMap<Page, GuardState>();
|
|
|
|
/**
|
|
* Wzorce ignorowane domyślnie:
|
|
* - 401 z sieci: oczekiwany (refresh bez sesji przy starcie, login z błędnym hasłem).
|
|
* Pozostałe statusy (403/404/5xx) nadal powodują FAIL.
|
|
*/
|
|
const DEFAULT_ALLOWED: RegExp[] = [
|
|
/Failed to load resource: the server responded with a status of 401/,
|
|
];
|
|
|
|
/**
|
|
* Test z automatycznym guardem błędów konsoli.
|
|
*
|
|
* Każdy test importujący `test` z tego pliku FAILUJE, jeśli na stronie pojawi się:
|
|
* - console.error (błąd z konsoli przeglądarki)
|
|
* - nieobsłużony wyjątek (pageerror)
|
|
*
|
|
* Assert dzieje się automatycznie w afterEach — nie trzeba nic deklarować w teście.
|
|
* Do ignorowania znanych, akceptowalnych błędów użyj `allowConsoleError(page, regex)`.
|
|
*/
|
|
export const test = base;
|
|
|
|
test.beforeEach(({ page }) => {
|
|
const state: GuardState = { issues: [], allowed: [...DEFAULT_ALLOWED] };
|
|
guards.set(page, state);
|
|
|
|
page.on('console', (msg) => {
|
|
if (msg.type() !== 'error') return;
|
|
const text = msg.text();
|
|
if (state.allowed.some((re) => re.test(text))) return;
|
|
state.issues.push({ kind: 'console.error', text });
|
|
});
|
|
|
|
page.on('pageerror', (err) => {
|
|
const text = `${err.message}${err.stack ? `\n${err.stack}` : ''}`;
|
|
if (state.allowed.some((re) => re.test(err.message))) return;
|
|
state.issues.push({ kind: 'pageerror', text });
|
|
});
|
|
});
|
|
|
|
test.afterEach(({ page }, testInfo) => {
|
|
const state = guards.get(page);
|
|
if (!state || state.issues.length === 0) return;
|
|
|
|
testInfo.annotations.push({
|
|
type: 'console-errors',
|
|
description: state.issues.map((i) => `[${i.kind}] ${i.text}`).join('\n'),
|
|
});
|
|
|
|
expect(
|
|
state.issues,
|
|
`Wykryto błędy konsoli / nieobsłużone wyjątki:\n${state.issues.map((i) => ` [${i.kind}] ${i.text}`).join('\n')}`,
|
|
).toEqual([]);
|
|
});
|
|
|
|
/**
|
|
* Dozwól ignorowania błędów konsoli pasujących do wzorca.
|
|
* Wywołaj w teście, np. `allowConsoleError(page, /znane ostrzeżenie biblioteki/)`.
|
|
*/
|
|
export function allowConsoleError(page: Page, pattern: RegExp) {
|
|
const state = guards.get(page);
|
|
if (state) state.allowed.push(pattern);
|
|
}
|
|
|
|
export { expect };
|