Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to console.log in playwright

I want to log one of the variables inside the playwright test case but am unable to load the log in developer tools console as I am using a page.on() function

test('largest contentful paint', async ({ page }) => {
  await page.goto('http://localhost:3000/', { waitUntil: 'networkidle' });

  const largestContentfulPaint = await page.evaluate(() => {
    return new Promise((resolve) => {
      new PerformanceObserver((l) => {
        const entries = l.getEntries();
        // the last entry is the largest contentful paint
        const largestPaintEntry = entries.at(-1);
        page.on('console', () => {
          console.log('largestPaintEntry', largestPaintEntry);
        });
        // resolve(largestPaintEntry.startTime);
      }).observe({
        type: 'largest-contentful-paint',
        buffered: true,
      });
    });
  });

  await expect(largestContentfulPaint).toBeLessThan(2500);
});
like image 366
KnightCrawler Avatar asked Dec 05 '25 20:12

KnightCrawler


1 Answers

As mentioned in a comment, the problem is that you must attach the page.on event handler outside the page.evaluate() callback.

// @ts-check
const { test, expect } = require('@playwright/test');

test('largest contentful paint', async ({ page }) => {
  await page.goto('https://www.stefanjudis.com/', { waitUntil: 'networkidle' });

  page.on('console', (msg) => {
    console.log(msg);
  });

  const largestContentfulPaint = await page.evaluate(() => {
    return new Promise((resolve) => {
      new PerformanceObserver((l) => {
        const entries = l.getEntries();
        // the last entry is the largest contentful paint
        const largestPaintEntry = entries.at(-1);
        console.log(largestPaintEntry.startTime)
      }).observe({
        type: 'largest-contentful-paint',
        buffered: true,
      });
    });
  });

  await expect(largestContentfulPaint).toBeLessThan(2500);
});
like image 146
stefan judis Avatar answered Dec 07 '25 10:12

stefan judis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!