e2e-testingplaywrightplaywright-testgui-testing

Having an await inside an expect as well as outside in playwright assertion statement


I was writing some tests in playwright for my application. I encountered an assertion

that passes when written like this -

await expect(await page.locator("#editor-banner > div:nth-child(1)").innerText()).toEqual("Some Heading");

and fails when written like this -

await expect(page.locator("#editor-banner > div:nth-child(1)").innerText()).toEqual("Some Heading");

Notice the await missing after expect in failed assertion.

I wanted some insights and approach related to my below doubts -

  1. if the passing assertion is written fine? I read in the doc https://playwright.dev/docs/best-practices#use-web-first-assertions about the best practices and looking at my assertion I don't think it is the right way. Is there a better way to write it in playwright? Please note that "Some Heading" is present in multiple places in page.

  2. the assertion that is failing is due to the fact that method .innerText() will return a promise that will resolve to a value only when we wait for it?

Thanks in advance!


Solution

  • toHaveText should work for you:

    await expect(page.locator("#editor-banner > div:nth-child(1)")).toHaveText("Some Heading");
    

    Regarding your questions:

    1. I think this is related to the other question you posted. You need to find some way to identify that element. That could be solved using a chain of locators. So you might be able to identify first the Parent and then a potential child.
    2. You're right. Without the await your are comparing a promise with a string.