Home > other >  How to check for some text on a webpage using playwright?
How to check for some text on a webpage using playwright?

Time:11-14

I want to check if the text QUEUED appears on a website. I tried the following commands

await expect(page1).toContainText('[QUEUED]');
await expect(page1.locator('span')).toContainText('[QUEUED]');

but in the first example it says a "locator" is expected, and for the second one it says

Error: strict mode violation: "span" resolved to 108 elements:

I am not interested in the exact element, I just want to check if the text QUEUED appears at least once on the page.

I also tried to select the exact element which in the HTML DOM looks like

<span data-v-729cd282="" >QUEUED</span>

using the expression

await expect(page1.locator('(//span[@data-v-729cd282])[6]')).toHaveText('[QUEUED]');

but here I also get an error

waiting for selector "(//span[@data-v-729cd282])[6]"

So how to do this right?

CodePudding user response:

In the first case you need a locator, in the second case your locator found too many elements.

You do need to be interested in the exact elements (even if it can be any element on page), how will you else locate them and assert if the text is present ?
You should find an element on the page by using the text as locator, and check if its present, thereby knowing the text is on page e.g.

const element = await page.getByText('QUEUED');
await expect(element !== undefined ).toBeTruthy();

so you should care about finding a element regardless of what element it is, as long as you'r trying to verify its presence on the page.

  • Related