skip to Main Content

Context: I want to test my react app with playwright. I have two Buttons who are nearly identical(The name of the both buttoons are bound to the same state, they always have the same name). Therefore i cant locate them with page.getByRole("button"); The just have different colors(one mui primary color the other secondary). I tried to differentiate them using xpath. Now my question why is it bad to use xpath? And what could be cleaner alternatives for my use case?

3

Answers


  1. XPath are not recommended as the DOM can often change leading to non resilient tests.
    You can get those buttons by their class

    await page.locator("//div[@class='mui-primary']")
    

    If you have no option then you can use xpath.

    Login or Signup to reply.
  2. Without showing your document structure, we can only guess what’d be better. The structural context matters greatly. Often, a parent container is necessary to disambiguate similar children.

    If the buttons have different text, aria labels or titles, you can select on that. If they have different parent containers, you could filter on those first using chained locators.

    You can also let Playwright can choose the best locator with its test generator.

    The reason XPath and CSS selectors are considered "last resort" is because they tend to be too closely coupled to implementation details like document structure and styling-oriented classes that don’t reflect how the user engages with the app.

    This warning applies as much to CSS selectors as XPath, but XPath in particular tends to result in highly brittle tests due to its tendency to be very precise about structure and properties.

    Other discouraged patterns include over-reliance on nth and test ids. As a rule of thumb, you want to be the right kind of precise ("button with text ‘Learn more’"), but not precise in the wrong way ("4th child of the first child of the 6th child of the 2nd paragraph nested within…."). Try to determine what characteristics make an element unique in a way that isn’t likely to change other than due to a meaningful adjustment, preferably something that a user might notice.

    See the docs for further details:

    XPath and CSS selectors can be tied to the DOM structure or implementation. These selectors can break when the DOM structure changes. Long CSS or XPath chains below are an example of a bad practice that leads to unstable tests:

    await page.locator(
        '#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > > input'
    ).click();
    
    await page
       .locator('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input')
       .click();
    

    I also caution against the "long selector chains" pattern in a Puppeteer antipatterns blog post (similar framework). If you do use CSS or XPath, try to avoid >, n-th and [class="something-too-specific"] and only use the bare number of ancestor containers necessary to disambiguate the element.

    React Testing Library follows a similar "don’t test implementation details" philosophy which has swept through the React world in the past few years and surely influenced Playwright.

    Login or Signup to reply.
  3. Using XPath as a locator in test automation is not necessarily
    considered bad in all cases, but it has some potential drawbacks and
    challenges that make it less preferable compared to other locator
    strategies.

    Here are a few reasons why XPath is sometimes discouraged:

    Fragility: XPath expressions can become fragile and prone to breaking when the structure of the HTML document changes. Even small changes in the DOM structure or the addition of new elements can cause XPath expressions to fail, requiring frequent updates and maintenance.

    Performance: XPath expressions tend to be slower compared to other locator strategies like CSS selectors. XPath traverses the entire DOM tree to find elements, which can impact the performance of your test automation, especially when dealing with large and complex web pages.

    Complexity: XPath expressions can be complex and difficult to read and understand, especially for those who are not familiar with XPath syntax. This can make the test code harder to maintain and debug, leading to increased effort and potential errors.

    Browser Compatibility: XPath support may vary across different browsers. While most modern browsers provide XPath support, there may be slight differences in how XPath is interpreted or implemented, leading to inconsistent behavior across different browser environments.

    Given these challenges, it is generally recommended to prefer other locator strategies like CSS selectors, class names, IDs, or any unique attributes whenever possible. These locators tend to be more readable, reliable, and performant.

    However, there may be cases where XPath is the only viable option, especially when dealing with complex DOM structures or when other locators cannot uniquely identify the desired elements. In such scenarios, it’s important to carefully construct XPath expressions that are specific, robust, and maintainable.

    Ultimately, the choice of locator strategy depends on the specific context, requirements, and limitations of your test automation project. It’s essential to evaluate the trade-offs and choose the most appropriate locator strategy that best suits your needs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search