Playwright Element Count Assertion Fix
In this tutorial, you'll learn about Playwright Element Count Assertion Fix. We cover key concepts, practical examples, and best practices.
Your toHaveCount() assertion fails — the count is wrong because the locator matches different elements than you expected.
The Problem
// WRONG — ambiguous locator matches too many elements
test('verify list items', async ({ page }) => {
await expect(page.locator('li')).toHaveCount(3);
// Fails if navigation or header also uses <li> elements
});
Expected: 3
Received: 7
The li locator matches ALL list items on the page, not just the ones in the specific list you're testing.
Step-by-Step Fix
1. Scope the locator
// RIGHT — scope locator before counting
import { test, expect } from '@playwright/test';
test('items in specific list', async ({ page }) => {
await page.goto('https://example.com');
const todoList = page.locator('.todo-list');
await expect(todoList.locator('li')).toHaveCount(3);
});
2. Use toHaveCount with filtering
// RIGHT — filter before counting
test('count active items', async ({ page }) => {
const allItems = page.locator('ul.items li');
const activeItems = allItems.filter({ hasText: 'Active' });
await expect(activeItems).toHaveCount(2);
});
3. Check count ranges
// RIGHT — range-based count verification
test('verify reasonable item count', async ({ page }) => {
const items = page.locator('table tr');
// Custom count check with soft assertion
const count = await items.count();
expect(count).toBeGreaterThanOrEqual(5);
expect(count).toBeLessThanOrEqual(50);
});
4. Use toHaveCount for dynamic lists
// RIGHT — wait for specific count
test('wait for items to load', async ({ page }) => {
await page.goto('https://example.com/search');
await page.getByRole('textbox').fill('playwright');
await page.getByRole('button', { name: 'Search' }).click();
// Wait until exactly 10 results appear
await expect(page.locator('.search-result')).toHaveCount(10, {
timeout: 10000,
});
});
Expected output:
✓ items in specific list (0.6s)
✓ count active items (0.5s)
✓ wait for items to load (2.3s)
Prevention Tips
- Scope locators to specific containers before counting
- Use
filterto narrow matching elements - Use
locator.count()for custom assertions - Use
toHaveCount()for auto-waiting count assertions - Set appropriate timeouts for dynamic content
Common Mistakes with assert count
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world PLAYWRIGHT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro