← Back to library
Playwrightassertionsbeginnerv1.20+
Count elements on the page
Assert an exact element count with toHaveCount(), or read the count for conditional logic.
1test('product grid renders the right number of cards', async ({ page }) => {
2 await page.goto('/products');
3
4 const cards = page.locator('[data-testid="product-card"]');
5
6 // toHaveCount() retries — prefer it over count() for assertions
7 await expect(cards).toHaveCount(12);
8
9 // Use count() when the number drives conditional logic
10 const n = await cards.count();
11 if (n > 6) {
12 await expect(page.getByTestId('pagination')).toBeVisible();
13 }
14});#count#toHaveCount#length#elements