如何为每个选项动态生成data-automation-id

时间:2020-02-03 12:48:28

标签: angular typescript angular-testing

我是Angular的新手。我已经写了一些代码。它包含两个下拉菜单。我正在使用简单的HTML selectoption标签。运行良好。但是质量检查小组表示,他们无法对其进行测试。如何在运行时分别为每个选项添加data-automation-id。我正在使用ngFor从同一数组中读取选项。这是我的代码。

mycalendar.component.html

<select data-automation-id="timeselection-mode-primary">
  <option *ngFor="let mode of modes">
      {{ mode }}
  </option>
</select>

...

<select data-automation-id="timeselection-mode-secondary">
  <option *ngFor="let mode of modes">
      Previous {{ mode }}
  </option>
</select>

不涉及任何反应形式。纯HTML标记。

mycalendar.component.ts

modes=['Year', 'Quarter', 'Sprint'];

有人可以告诉我如何在运行时生成自动化ID。还是我问错了一个问题,浪费了每个人的时间。在这种情况下,请提出替代方案。

2 个答案:

答案 0 :(得分:1)

将您的选择放入迭代两次的ngFor中,并将其索引指定为data-automation-id。 或者,您可以调用一个生成随机ID data-automation-id="generateRandom()"

的函数

答案 1 :(得分:1)

要动态为选项赋予数据属性,请尝试使用[attr.data-*]向选项添加属性。

<option *ngFor="let mode of modes; let i = index;" [attr.data-automation-id]='i'>
      {{ mode }}
</option>

Working example here...