循环遍历定位器数组并在 Typescript Playwright 中应用断言

huangapple go评论80阅读模式
英文:

Loop through an array of Locators and apply assertion in Typescript Playwright

问题

我有一个定位器数组,我需要运行一个断言来验证它是否包含特定的文本。我知道这可以在循环中完成,但似乎这是一种繁琐的方法,我想改进它。

Tedius approach:

let textIsPresent: boolean = false;

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

expect(textIsPresent).toBe(true);

是否有更好的方法来做到这一点?例如,使用匿名函数或甚至内置的智能函数吗?我对JavaScript/TypeScript不太熟悉,感谢任何支持。谢谢。

英文:

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

答案1

得分: 1

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

使用 Playwright 的原生方法来获取所有匹配节点的 innerText。

参考链接:https://playwright.dev/docs/api/class-locator#locator-all-inner-texts

英文:
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

答案2

得分: 0

以下是翻译好的部分:

You may also filter locators based on text:

await expect(page
    .getByRole('listitem'))
    .toHaveText(['apple', 'banana', 'orange']);
英文:

You may also filter locators based on text:

await expect(page
    .getByRole('listitem'))
    .toHaveText(['apple', 'banana', 'orange']);

答案3

得分: 0

const ele = page.locator([data-test-id='myId'] >> text=MyText);

英文:

You can also combine a locator selection with desired text:

const ele = page.locator(`[data-test-id='myId'] >> text=MyText`);

huangapple
  • 本文由 发表于 2023年3月31日 23:57:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定