skip to Main Content

I have an Array of Locators and I need to run an assertion to verify if it contains certain text. I am aware that this can be done in a loop however it seems like a tedious approach and I would like to improve it.

Tedius approach:

  let textIsPresent : boolean = false;

  for (let entry of arrayOfLocators) {
    if(arrayOfLocators[entry].innerText().toContain("myText")){
       textIsPresent = true;
       break;
    }
  }

  expect(textIsPresent).toBe(true)

Is there a better way to do this? For example, using annonymous functions or even built in smart functions? I’m not too strong with Javascript/Typescript and would appreciate any support. Thank you

3

Answers


  1. const texts = await page.getByRole('link').allInnerTexts();
    expect(texts).toContain(true)
    

    Native playwright approach to get the innertext from all matching nods.

    Reference: https://playwright.dev/docs/api/class-locator#locator-all-inner-texts

    Login or Signup to reply.
  2. You may also filter locators based on text:

    await expect(page
        .getByRole('listitem'))
        .toHaveText(['apple', 'banana', 'orange']);
    
    Login or Signup to reply.
  3. You can also combine a locator selection with desired text:

    const ele = page.locator(`[data-test-id='myId'] >> text=MyText`);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search