How can I create a locator from a link with a unique href in Playwright?
I was recently asking myself this very same questions. With all the great locator tooling out there, sometimes there is just an old piece of legacy code that isn't going to get modified to add a data test id or other unique locator. In those situations we can utilize CSS selectors!
The HTML in question is provided below. The only unique value I could find was the href value for this link. With this webpage, depending on the API calls the notification span may or may not be present, and the number 100
could be any number.
<li class="nav-item">
<a class="nav-link" href="#/admin/messages">
<i class="fa fa-inbox" style="font-size: 1.5rem;">
<span class="notification">100</span>
</i>
</a>
</li>
I wanted to create a test that would validate the span inside the link had the correct count I was expecting. My solution was to utilize the CSS Attribute selector in the page.locator(). In the below example I first locate the higher level link <a> tag, by the href, assigned that to a variable named messageLink
and then set a new variable messageCountSpan
and used the messageLink
locator using chaining, getting the span inside the link and returning that as a locator.
const messageLink = page.locator('[href*="#/admin/messages"]')
const messageCountSpan = messageLink.locator("span");
await expect(messageCountSpan).toHaveText(`${count}`);
A few other helpful resources that helped me on my own learning journey.
Thanks for reading! If you found this helpful, reach out and let me know on LinkedIn or consider buying me a cup of coffee. If you want more content delivered to you in your inbox subscribe below.