πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 99 of 100
Core Concepts
Intermediate

What is a 'strict mode violation,' and how do you resolve it?

The Answer

A strict mode violation occurs when a locator matches more than one element and a single-element action is attempted. Playwright throws an error listing all matched elements to help you diagnose and fix the selector.

Deep Dive Explanation

The error message Playwright provides is intentionally verbose β€” it lists ALL matched elements with their HTML. Use this output to understand WHY your locator is ambiguous, then choose the fix that adds the least fragility. Adding a `data-testid` is the nuclear option β€” reserve it for cases where semantic differentiation is genuinely impossible.

example.spec.ts
// ERROR: strict mode violation: locator('a.btn') resolved to 4 elements:
// 1. <a class="btn" href="/login">Login</a>
// 2. <a class="btn" href="/register">Register</a>
// 3. <a class="btn" href="/forgot">Forgot Password</a>
// 4. <a class="btn" href="/help">Help</a>

// ❌ Ambiguous locator
await page.locator('a.btn').click(); // Throws!

// βœ… Fix 1: Add semantic specificity
await page.getByRole('link', { name: 'Login' }).click();

// βœ… Fix 2: Scope to parent
await page.locator('header').getByRole('link', { name: 'Login' }).click();

// βœ… Fix 3: Filter
await page.locator('a.btn').filter({ hasText: 'Login' }).click();

// βœ… Fix 4: Add data-testid in app code (for truly ambiguous cases)
// <a class="btn" data-testid="login-btn" href="/login">Login</a>
await page.getByTestId('login-btn').click();