skip to Main Content

Given the following html:

...
<div class="table">
  <div role="row" row-id="1">...</div>
  <div role="row" row-id="2">...</div>
<div>
...

How can I use the getByRole('row') locator to get the div with row-id="1"?

Using getByRole('row').filter('[row-id="1"]') doesn’t work as filter seems to be applied on the child elements only.

However according to the documentation, the filter locator "is queried starting with the outer locator match", so the filter should actually work? Am I missing something?

Using the argument options.name of getByRole() is not an option.

2

Answers


  1. You can use the and locator.

    await expect(page.getByRole("row").and(page.locator('[row-id="1"]'))).toHaveText("1 ROW");
    

    But I think you can solve that with just one CSS expression.

    await expect(page.locator(".table [row-id='1']")).toHaveText("1 ROW");
    
    Login or Signup to reply.
  2. If you’re trying to assert on the text content, the cleanest approach is to use getByRole‘s name: key:

    import {expect, test} from "@playwright/test"; // ^1.42.1
    
    const html = `<!DOCTYPE html><html><body>
    <div class="table">
      <div role="row" row-id="1">A</div>
      <div role="row" row-id="2">B</div>
    <div>
    </body></html>`;
    
    test("Row 1 has text 'A'", async ({page}) => {
      await page.setContent(html);
      await expect(page.getByRole("row", {name: "A", exact: true})).toBeVisible();
    });
    

    If you don’t want to assert on the text, :scope is also possible, allowing you to include the current node in the query context:

    const row = page.getByRole("row").locator('[row-id="1"]:scope');
    

    I generally avoid .filter() because the syntax is rather confusing–it uses a has: key in its object argument, breaking off of the main locator call chain.

    If you’re scraping rather than testing, then I’d just use plain CSS as suggested in this answer.

    That said, you may want to provide more context for your use case (full HTML tree, with containers) because there could be a better way to do this. If row-ids are unique, then they’re effectively data-testids, which can be queried directly, without the getByRole context query.

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