typescriptplaywrightplaywright-testplaywright-typescript

toBeVisible count of onscreen items


I'm unsure if I've missed something, but I need to:

  1. Check an item is visible on screen (code below which is working)
  2. Do a count on the number of visible items on screen

Originally I was doing:

 test('Desktop check - (Optimal on desktop / tablet) only shown on smaller screens (i.e mobile breakpoint)', async ({ page, isMobile }) => {
    test.skip(isMobile)
    await page.goto(url);
    const buttonsCount = await page.getByText('(Optimal on desktop / tablet)').count();
    expect(buttonsCount).toBe(0);
  });

But this was also finding all of the hidden versions of this test, so whilst I was expecting 0, it was returning 1.

Easy fix for part one was to switch to .toBeVisible(), but then there is no count property on .toBeVisible() I can access.

How can I do a count on toBeVisible? Or should I do a loop count and pass that into a .toBe()?


Solution

  • Maybe easiest of the options is applying filter method to your getByText().

    const buttonCount = await page.getByText('(Optimal on desktop / tablet)')
      .filter({ visible: true })
      .count()
    

    See Matching only visible elements

    If you look at the section below that Count items in a list there is a specific assertion toHaveCount() you may use.

    expect(page.getByText('(Optimal on desktop / tablet)').filter({ visible: true }))
      .toHaveCount(0)
    

    This is my minimal proof test:

    test('filtering by visible', async ({ page }) => {
    
      const html = `
        <html><body>
          <button style="display:none">(Optimal on desktop / tablet)</button>
        </body></html>
      `
      await page.setContent(html);
    
      const visibleButtons = page.getByText('(Optimal on desktop / tablet)')
        .filter({ visible: true })
      await expect(visibleButtons).toHaveCount(0)
    })
    

    enter image description here

    If I remove the display:none style, I can see the test failing which means the test meets expectations.

    enter image description here