GoogleChrome / web-vitals

Essential metrics for a healthy site.
https://web.dev/vitals
Apache License 2.0
7.49k stars 410 forks source link

How to inject web-vitals library function in playwright browsers environment ? #316

Closed iamAfrontendDev closed 11 months ago

iamAfrontendDev commented 1 year ago

I am trying to get a web-vitals metrics result from the reportWebVitals function from the web-vitals npm package but unable to achieve the result using playwright, it throws an error saying "page. evaluate: ReferenceError: _reportWebVitals is not defined"

import type { ReportHandler } from 'web-vitals';

const reportWebVitals = (onPerfEntry?: ReportHandler) => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;
import reportWebVitals from '../src/reportWebVitals';
import { Browser, chromium, expect, test } from '@playwright/test';
import { Page } from 'playwright';

const HOME_PAGE_URL = 'http://localhost:4000/';

test.only('Performance Checks using web-vitals library', async ({ browser }) => {
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto(HOME_PAGE_URL, { waitUntil: 'networkidle' });
  const getVitals = (args) => {
    console.log('args', args);

  };
  await page.evaluate(async () => {
    reportWebVitals(getVitals);
  });
});
tunetheweb commented 11 months ago

I'm afraid I don't use Playwright and can't really advise but see #180 as one implementation that someone has used (based on an older version of web-vitals) in case that helps.