英文:
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("#favorite-colors")
element.select_option("Colorado -- CO")
selected_label = select_elem.evaluate("el => el.options[el.selectedIndex].text")
assert selected_label == "Colorado -- CO"
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论