typescriptplaywrightplaywright-test

.count() returns 0 but .nth()/first()/last() does return element


Selector this.table is working. I verified the locator by npx playwright open --> Pick locator. The table has 50 rows but 27 are filled. The 27 rows are <tr id=xx ...>...</tr>, the rest <tr>...</tr>. I only get the rows which have an id attribute.

constructor(page: Page) {
        this.page = page
        this.dialog = page.getByRole("dialog").locator("div")
        this.table = this.page.locator(".table-body").locator("tbody").locator("tr[id]")
    }

I am using @playwright/test 1.36.1. When I invoke .count() (expecting 27) I get 0:

test("update entity", async ({page}) => {
        const payload = my_object.table
        console.log(await payload.count())
    })

When I use .all() I get []:

test("update entity", async ({page}) => {
        const payload = my_object.table
        console.log(await payload.all())
    })

When I use .nth(0), first() or .last() I receive correct data:

test("update entity", async ({page}) => {
        const payload = my_object.table
        console.log(await payload.first().innerText())
    })

What am I doing wrong?


Solution

  • This could be because .all() (nor .count()) don’t necessarily wait for the locator to be visible (ref. documentation), unlike .first(), .last() and .nth(0). Try asserting the locator to be visible, and the do an .all():

    test("update entity", async ({ page }) => {
        const payload = my_object.table
        await expect(payload.first()).toBeVisible() // or another appropriate assertion to assert that page is loaded
        console.log(await payload.all())
    })