* Count how many elements on the page match a given selector candidate * Used to check if a selector is unique
(candidate)
| 295 | * Used to check if a selector is unique |
| 296 | */ |
| 297 | function countMatchingElements(candidate) { |
| 298 | try { |
| 299 | if (candidate.method === 'getByRole') { |
| 300 | const role = candidate.role; |
| 301 | const name = candidate.name; |
| 302 | |
| 303 | // Find all elements with this role |
| 304 | const allElements = document.querySelectorAll('*'); |
| 305 | let count = 0; |
| 306 | |
| 307 | for (const el of allElements) { |
| 308 | if (getAriaRole(el) === role) { |
| 309 | if (name) { |
| 310 | // Check if accessible name matches |
| 311 | if (getElementAccessibleName(el) === name) { |
| 312 | count++; |
| 313 | } |
| 314 | } else { |
| 315 | count++; |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | return count; |
| 320 | } |
| 321 | |
| 322 | if (candidate.method === 'getByLabel') { |
| 323 | const label = candidate.label; |
| 324 | const allElements = document.querySelectorAll('input, select, textarea, button'); |
| 325 | let count = 0; |
| 326 | for (const el of allElements) { |
| 327 | const labels = getElementLabels(el); |
| 328 | if (labels.some(l => l.normalized === label)) { |
| 329 | count++; |
| 330 | } |
| 331 | } |
| 332 | return count; |
| 333 | } |
| 334 | |
| 335 | if (candidate.method === 'getByPlaceholder') { |
| 336 | return document.querySelectorAll(`[placeholder="${CSS.escape(candidate.placeholder)}"]`).length; |
| 337 | } |
| 338 | |
| 339 | if (candidate.method === 'getByTestId') { |
| 340 | return document.querySelectorAll(`[data-testid="${CSS.escape(candidate.testId)}"]`).length; |
| 341 | } |
| 342 | |
| 343 | if (candidate.method === 'locator') { |
| 344 | return document.querySelectorAll(candidate.selector).length; |
| 345 | } |
| 346 | |
| 347 | if (candidate.method === 'getByText') { |
| 348 | const text = candidate.text; |
| 349 | const allElements = document.querySelectorAll('*'); |
| 350 | let count = 0; |
| 351 | for (const el of allElements) { |
| 352 | const elText = elementText(el).normalized; |
| 353 | if (elText === text || elText.includes(text)) { |
| 354 | count++; |
no test coverage detected