英文:
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`);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论