collect.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { Page } from '@playwright/test';
  2. /** 已知的第三方库废弃警告 / React 开发态噪音,不计入问题清单 */
  3. const NOISE =
  4. /Spin.*deprecated|destroyOnClose|Dropdown\.Button.*deprecated|ProList.*deprecated|Alert.*deprecated|React does not recognize|Invalid DOM property|empty string \(""\) was passed|Static function can not consume|React DevTools/;
  5. /**
  6. * 挂上 console / pageerror / 请求失败 / HTTP 4xx-5xx 采集。
  7. * 这是本套测试的核心——它替代的正是"人肉盯着 devtools 控制台"这件事。
  8. */
  9. export function collect(page: Page) {
  10. let logs: string[] = [];
  11. page.on('console', (m) => {
  12. const t = m.type();
  13. if ((t === 'error' || t === 'warning') && !NOISE.test(m.text())) {
  14. logs.push(`[${t}] ${m.text().slice(0, 250)}`);
  15. }
  16. });
  17. page.on('pageerror', (e) => logs.push(`[PAGEERROR] ${e.message.slice(0, 250)}`));
  18. page.on('requestfailed', (r) =>
  19. logs.push(`[REQFAIL] ${r.url()} :: ${r.failure()?.errorText}`)
  20. );
  21. page.on('response', (r) => {
  22. if (r.status() >= 400) logs.push(`[HTTP ${r.status()}] ${r.url()}`);
  23. });
  24. return {
  25. /** 当前累积的日志 */
  26. get all() {
  27. return logs;
  28. },
  29. reset() {
  30. logs = [];
  31. },
  32. /** 打印某个测试步骤采集到的内容并清空 */
  33. dump(step: string) {
  34. console.log(`\n### ${step}`);
  35. logs.length ? logs.forEach((l) => console.log(' ' + l)) : console.log(' (clean)');
  36. logs = [];
  37. },
  38. };
  39. }