基于选项文本的下拉选择框的期望值

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

Expect value of a dropdown select based on option text

问题

我们有一个下拉选择框

<select id="favorite-colors" multiple>
  <option value="R">红色</option>
  <option value="G">绿色</option>
  <option value="B">蓝色</option>
</select>

在Playwright中,我们可以使用以下代码来检查值

expect(locator).to_have_values([re.compile(r"R"), re.compile(r"G")])

参见:https://playwright.dev/python/docs/api/class-locatorassertions#locator-assertions-to-have-values

但是我如何使用expect来检查选择是"红色"还是"绿色"还是"蓝色" - 而不是值(R, G, B),而是基于选项的文本。
我们没有"selected"的指示器 - 如果一个选项被选中,我应该如何期望?

英文:

We have a dropdown select

<select id="favorite-colors" multiple>
  <option value="R">Red</option>
  <option value="G">Green</option>
  <option value="B">Blue</option>
</select>

In playwright we can use to check the value

expect(locator).to_have_values([re.compile(r"R"), re.compile(r"G")])

See: https://playwright.dev/python/docs/api/class-locatorassertions#locator-assertions-to-have-values

But how can I use the expect to check if the selection is "Red" or "Green" or "Blue" - so instead of the value (R, G, B), base on the text of the options
We do not have indicator for "selected" - how should I expect if an option selected?

答案1

得分: 1

值是发送到后端的内容,所以如果你想要值是完整的字符串(Red, Green, Blue),你需要在HTML代码中指定它。

在Playwright中,以下代码可以实现:

expect(locator).to_have_values([re.compile(r"Red"), re.compile(r"Green")])


<details>
<summary>英文:</summary>

<select id="favorite-colors" multiple>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>


The value is what is sent to the backend, so if you want the value to be the full string (Red, Green, Blue), you have to specify it in the html code.

In playwright, the following code should do it:

expect(locator).to_have_values([re.compile(r"Red"), re.compile(r"Green")])


</details>



# 答案2
**得分**: 1

似乎,这应该可以工作

        element = page.locator("#favorite-colors")
        element.select_option("Colorado -- CO")
        selected_label = select_elem.evaluate("el => el.options[el.selectedIndex].text")
        assert selected_label == "Colorado -- CO"

<details>
<summary>英文:</summary>

Seems, this should work

        element = page.locator(&quot;#favorite-colors&quot;)
        element.select_option(&quot;Colorado -- CO&quot;)
        selected_label = select_elem.evaluate(&quot;el =&gt; el.options[el.selectedIndex].text&quot;)
        assert selected_label == &quot;Colorado -- CO&quot;

</details>



huangapple
  • 本文由 发表于 2023年3月9日 17:10:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682481.html
匿名

发表评论

匿名网友

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

确定