Background : There is an old code base in React where I am writing E2E Playwright tests. Almost 80% of the codebase doesn't have valid role attributes in html elements, input elements are implemented via a plain div, buttons are implemented via div, html elements like text area, checkbox doesn't have role attributes and the list goes on. Since I cannot rely on complex class based or Xpath selectors as these changes frequent so while Playwright writing tests I am struggling to locate my elements in a resilient manner.
I am following the below approach to locate my elements as of now -
Wrapping elements with data-testid
attribute or id
attribute wherever possible to locate the target element and then running assertions on it.
Problem that this approach doesn't solve : There are cases where I am writing complex selectors like for example :
page.locator("#model-params-editor > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) span").innerText()
just to get the text inside a span
.
I cannot do getByText
in above example because there are more than one elements having the same text and even if I filter out the one that I need anyhow the locator might not work in future if the other matching text gets removed from the page due to some business reason.
Also if I put a data-testid
or id attribute to span
then in the same page that span is used in multiple places so each of that span will have that data-testid or id attribute and when I will locate the one that I need it will be a problem in filtering out the one that I need and it doesn't look resilient also because in future the other spans might not be there and my current filtering logic will fail.
Looking at the above locator, if there is any change in HTML the locator will break in future as it is complex and fragile.
Can anyone please suggest me some practical ways to make my test resilient considering my current situation. Thank you in advance!