Rayrun
โ† Back to Discord Forum

Should I use `to_be_visible()` like this?

philcollinslosersonposted in #help-playwright
Open in Discord
philcollinsloserson
philcollinsloserson
def assert_benefits_container_text(self) -> None:
        """Assertions for benefits container"""
        locator = self.page.locator("div.benefits-container ul li")
        expect(locator.nth(0)).to_have_text("No Cost Transition")
        expect(locator.nth(0)).to_be_visible()```

This thread is trying to answer question "Is the use of `to_be_visible()` in the shared Python code snippet correct, and can it be improved?"

4 replies

Yeah, that should work fine. The only thing I'd recommend is using a better locator if possible; the Playwright Locators guide (https://playwright.dev/python/docs/locators) is fantastic. div.benefits-container ul li seems like it could be brittle, and it's best to avoid nth() methods. Without seeing your app, I can't recommend a better locator, but to avoid the nth(0) you could probably do expect(locator.get_by_text("No Cost Transition")).to_be_visible() in place of your last 2 lines.

disclaimer: I use typescript instead of python for Playwright, so my suggestion code is untested and might be bad syntax

philcollinsloserson
philcollinsloserson

Ah thank you Julie!

I figured that it would be better to move away from finding all the things by text - but ... thinking about it for 2 seconds should have made me realize that's not actually the case ๐Ÿ˜…

Thank you for your help!

you're welcome!

I avoid using only text as a locator and tend to use chaining/filtering with text to narrow things down.

So in your case, I'd find a different locator for the benefits container, either a data-testid or a role, and then chain like locator.get_by_text(). Not sure what the filtering syntax is for python, but it's very handy so definitely read up on that ๐Ÿ˜„

philcollinsloserson
philcollinsloserson

Oh I appreciate the clarification about using only text as a locator.. I will keep that in mind!

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.