【问题标题】:How can I select a somewhat dynamic ID based on the index position?如何根据索引位置选择有点动态的 ID?
【发布时间】:2020-10-22 01:32:07
【问题描述】:

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

在一个下拉菜单中,有 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)')

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

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

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

【问题讨论】:

    标签: typescript testing automated-tests ui-automation testcafe


    【解决方案1】:

    您通过部分属性值选择元素的方法是正确的。另外,您可以使用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));
    });
    

    【讨论】:

    • 这行得通!谢谢!很高兴知道我的方法正确,但执行错误。
    【解决方案2】:

    在 Javascript 中,您可以使用以下代码,它会为您提供所有以 _ButtonId 结尾的 id 数组。

    document.querySelectorAll('[id$="_ButtonId"]')
    

    之后,您可以使用 index 访问您希望访问的任何元素。

    【讨论】:

      猜你喜欢
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2012-09-12
      相关资源
      最近更新 更多