Category: testing

Playwright: Count all the components on the page

Is it possible that you have to debug Playwright and list all the available items on the page, so you can know if your locate your item const buttons = await page.$$(‘button’); or your click await buttonButton1.click() will work. To do so you can list all items and also highlight them when you run npx playwright test , add the following in your playwright test file, in any test:

  const componentHandles = await page.evaluateHandle(() => {
    const components = new Map();
    const walker = document.createTreeWalker(
      document.body,
      NodeFilter.SHOW_ELEMENT,
    );

    while (walker.nextNode()) {
      const element = walker.currentNode as HTMLElement;
      const nodeName = element.nodeName.toLowerCase();
      if (components.has(nodeName)) {
        components.set(nodeName, components.get(nodeName) + 1);
      } else {
        components.set(nodeName, 1);
      }
      element.style.border = '2px solid red'; // Highlight the component
    }

    return Array.from(components);
  });

  const componentCount = await componentHandles.jsonValue();

  console.log('Component count:');
  for (const [component, count] of Object.entries(componentCount)) {
    console.log(`${component}: ${count}`);
  }

Result:

0: noscript,1
1: script,1
2: div,41
3: input,3
4: span,3
5: aside,1
6: style,1
7: button,2
8: svg,1
9: g,2
10: path,3

And it will display on the web browser you item with red borders.