Home > Enterprise >  Is it safe to use selectors different then IDs in web testing?
Is it safe to use selectors different then IDs in web testing?

Time:01-29

I worked with cypress for few months and I get used to work with data-auto-id which is basically unique selector in my understanding.

<button data-auto-id="my-nice-button">

and then i can select it in cypress cy.get([data-auto-id='my-nice-button']...

Now i tried playwright but selecting by text or stuff like this seems pretty unsafe for me. Example from their website:

await page.locator('article:has-text("Playwright")').click();

What is considered safe approach? Should I use IDs in playwright or can I jump into CSS, text and other selectors? Please note that I have no real world experience so I don't know what's considered best practice. This question is not opinion based its more like is it safe or no?

CodePudding user response:

Luckily for us, Playwright was many different selector engines. You can pick the one that suits better for your scenario. Playwright also describes a good set of best practices. For instance:

  • Attributes like text content, input placeholder, accessibility roles, and labels are user-facing attributes that change rarely. These attributes are not impacted by DOM structure changes.
  • When user-facing attributes change frequently, it is recommended to use explicit test ids, like data-test-id. These data-* attributes are supported by the CSS and id selectors.
  • And, XPath and CSS can be tied to the DOM structure or implementation. These selectors can break when the DOM structure changes.

If your team consistently uses data- attributes, you can keep using them.

  •  Tags:  
  • Related