我怎样才能 select 基于索引位置的有点动态的 ID?

How can I select a somewhat dynamic ID based on the index position?

我会先解释一下我的意思。

在下拉菜单中,有 5 个按钮,其中 2 个具有静态 ID(意味着它们是硬编码的),其中 3 个可以通过不同的微服务进行更改(例如,当您更改中断类型时) .这 3 个按钮的 ID 是根据中断类型的名称生成的,但它们总是以“_ButtonId”结尾,并且通常包含单词“Break”。

它看起来像这样,我从 div 中删除了所有其他内容以使其简短:

  <div class="user-status__group">
   <button id="logoutButtonId"  </button>
   <button id="activateButtonId"  </button>
   <button id="RestroomBreak_ButtonId"  </button>
   <button id="LunchBreak_ButtonId" </button>
   <button id="TechnicalBreak_ButtonId"  </button>
 </div>

我使用 testcafe,我想要实现的是能够为这些休息设置 3 个不同的按钮。 像 breakButtonOne = *break_ButtonId[1] 这样的东西 breakButtonTwo = *break_ButtonId[2]

我根据我在网上阅读的内容/通过文档尝试了类似的方法:

  private breakBtnOne = Selector("[id$='_ButtonId']:eq(1)");

  private breakBtnOne = Selector('[id$="_ButtonId"]:nth-child(1)')

这似乎不起作用,第一个 returns 一个错误,它不是一个有效的选择器,第二个找不到按钮,在这种情况下,是该列表中的第一个中断按钮.

你能给我指明正确的方向吗?我检查了一些 testcafe 文档,但它建议我应该使用属性而不是 ID,这对我来说不是一个选项,因为整个 UI 有反应 components/containers 和一些 UI 片段。 ID 基于 UI 片段中的内容,它们不是静态的,但仍保留类似 ThisSection_anId_ButtonId 的内容,并且属性会发生变化。

我正在使用这个基本示例,所以我可以理解我应该如何进一步进行,因为我完全不是 TypeScript / JS 方面的专家。感谢您的宝贵时间!

在 Javascript 中,您可以使用下面的代码,它将为您提供所有以 _ButtonId.

结尾的 ID 的数组
document.querySelectorAll('[id$="_ButtonId"]')

之后你可以使用索引来访问任何你想访问的元素。

您通过部分属性值选择元素的方法是正确的。此外,您可以使用nth方法来查找具有指定索引的元素。

请参考以下文章:

https://devexpress.github.io/testcafe/documentation/reference/test-api/selector/nth.html

https://devexpress.github.io/testcafe/documentation/guides/basic-guides/select-page-elements.html#select-elements-with-dynamic-ids

我创建了一个示例来演示它是如何工作的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="user-status__group">
    <button id="logoutButtonId">b1</button>
    <button id="activateButtonId">b2</button>
    <button id="RestroomBreak_ButtonId">b3</button>
    <button id="LunchBreak_ButtonId">b4</button>
    <button id="TechnicalBreak_ButtonId">b5</button>
</div>
</body>
</html>

测试代码:

import { Selector } from 'testcafe';

fixture `fixture`
    .page `D:\projects\tests\index.html`;

test('test', async t => {
    await t.click(Selector('[id$=_ButtonId').nth(0));
    await t.click(Selector('[id$=_ButtonId').nth(1));
    await t.click(Selector('[id$=_ButtonId').nth(2));
});