I'm unsure if I've missed something, but I need to:
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()
?
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)
})
If I remove the display:none
style, I can see the test failing which means the test meets expectations.