给出以下代码:
cy.intercept('POST', 'get_time_slots', { fixture: data }).as('getTimeslotList');
cy.get('input.datepicker').type("2024-01-10").trigger('change');
cy.get("checkbox#flexCheckDefault").click()
说明:
cy.get('input.datepicker').type("2024-01-10").trigger('change')
命令将触发对get_time_slots
API,返回时隙列表 - 由固定文件模拟Note: Changing the date value is the only way to trigger the api call
cy.get("checkbox#flexCheckDefault").click()
命令将向 UI 显示时间段列表,但奇怪的是:- 它还调用
get_time_slots
API 1 次 - 如果通过 UI 手动单击该复选框,则不会发生此行为
- 它还调用
组件源代码:
日期选择器
<input
placeholder="Select date" type="date"
class="form-control date-input-custom datepicker"
t-att-max="state.maxDate"
t-att-disabled="this.checkDatePickerDisable()"
t-att-min="state.todayLabel"
t-on-change="(e) => this.onSelectDate(e.target.value)"
t-att-value="state.appointment.booking_date" />
复选框:
<input
type="checkbox" value=""
id="flexCheckDefault"
t-on-input="this.showSlot" />
(我在使用 .check()
而不是 click()
时遇到了同样的问题)
以前有人遇到过这个问题吗?如何解决?
最佳答案
我猜想发生 change
事件的双重发生是因为应用程序已经设置为在元素失去焦点时触发 change
。
当单击第二个元素时,会发生这种情况,请参阅 Focus 处的 .click()
文档。
Focus
Focus is given to the first focusable element For example, clicking a inside of a gives the focus to the button...
如果这是真的,您可以省略 .trigger('change')
并添加 .blur()
。
cy.intercept('POST', 'get_time_slots', { fixture: data }).as('getTimeslotList');
cy.get('input.datepicker').type("2024-01-10") // see docs - unsafe to chain
cy.get('input.datepicker').blur()
cy.wait('@getTimeslotList') // you have this but have not shown it in the test code
cy.get("checkbox#flexCheckDefault").click()
It is unsafe to chain further commands that rely on the subject after
.type()
如果应用程序触发了 change
事件,则尤其如此 - DOM 可能会重新渲染。为了安全起见,请为下一步操作发出另一个 cy.get('input.datepicker')
。
关于testing - 点击 Cypress 中的元素后自动调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77754004/