【问题标题】:Cypress - select an option without using text or value赛普拉斯 - 选择一个选项而不使用文本或值
【发布时间】:2018-12-10 15:54:03
【问题描述】:

这是我要选择的:

<select id="firstDate" name="firstDate" class="ab-abcd sdfg">
<option disabled="" value="">First day</option>
<option value="01.02.2019">01.02.2019</option>
<option value="01.02.2019">01.02.2019</option>
</select>

这个日期会不时改变,所以有没有办法在不使用 Cypress 的情况下选择一个选项

cy.get('#firstDate').select('01.01.2019')

?

我也试过

cy.get('#firstDate').first()

但这似乎不起作用。

【问题讨论】:

    标签: testing automation qa cypress


    【解决方案1】:

    我认为更改值的最佳方法是通过.select()。如果您尝试强制单击某个选项,它不会更改所选值。

    使这个值发生变化的原因是什么?如果它们是从服务器请求生成的,您可以尝试将其存根 like this。如果它们是在当前日期生成的,你可以试试using clocks

    在知道是什么使选择器动态之后编辑:

    要确定测试日期并使其保持一致,您可以这样做

    // fix the date before rendering the select
    const now = new Date(2019, 01, 15).getTime() //  2019-01-02 timestamp
    cy.clock(now)
    
    cy.visit('/index.html') // visit the page to test (or make actions that render the select)
    cy.get('#firstDate').select('01.02.2019') // select one month beyond
    cy.get('#firstDate').select('01.03.2019') // select two months beyond
    

    亚历克斯

    【讨论】:

    • 存根是最好的主意。在测试中使用可预测的内容总是更好。
    • 嗯,这是用于注册的,所以这是一个开始日期,它将永远在未来 - 未来 + 一个月的第一天和未来 + 两个月的第一天.
    • 我已经用针对您的用例的特定代码更新了我的答案。我使用clock() 来固定时间并使测试一致
    【解决方案2】:

    感谢您的回答。与此同时,我找到了一个适合我的解决方案:

        cy.get('#FirstDate')
       .find('option')
       .then($elm => $elm.get(1).setAttribute('selected', "selected"))
       .parent()
       .trigger('change')
    

    但我也会尝试你的建议,让你知道发生了什么。

    【讨论】:

    • 感谢您回答您自己的问题!欣赏这个!
    【解决方案3】:

    您的第二次尝试非常接近,但您得到的是 select 元素,而不是 option 元素。试试这个:

    cy.get('select#firstDate').click() // Open the dropdown
    cy.get('select#firstDate > option')
      .eq(1) // The second option, because the first is a heading
      .click()
    

    【讨论】:

    • 谢谢,我试过了,但我得到了这个错误信息:“CypressError: Timed out retrying: cy.click() failed because this element is not visible: 这个元素'
    • 你是先打开下拉菜单吗?我猜它没有打开。先加cy.get("select#firstDate").click()。我会更新我的答案
    • 但是我怎样才能点击一个选择元素呢?这会引发错误
    • 啊,第一个元素不是您可以单击的选项之一,它是标题“第一天”。您必须选择 second 元素,您可以使用 .eq(1) 而不是 .first() 来做到这一点。在阅读您对@AlexSerra 的回答的评论以提供更多上下文后,您可以将状态设置为一致,这将允许您使用.select()。这是一种更好的处理方式,因为您可以知道要选择的值。
    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2021-12-11
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多