testing - 点击 Cypress 中的元素后自动调用 API

标签 testing automated-tests cypress cypress-intercept

给出以下代码:

  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 手动单击该复选框,则不会发生此行为

enter image description here


组件源代码:

日期选择器

<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()

Docs .type()

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/

相关文章:

java - 我可以将java测试复制到Katalon studio吗

Cypress 检查元素是否有滚动条可见

javascript - 检查元素是否在 cypressIO 中按字母顺序排序

django - 我应该为每个应用程序创建一个 factories.py 吗?

perl - 在 Perl 的 Test::More 中声明后如何使用参数 `tests`?

java - 如何在同一个浏览器窗口中依次运行一组 Cucumber 功能文件?

protractor - 在 afterEach block 中放置一个断言是一个好习惯吗?

node.js - Cypress 安装失败

php - 如何在 Behat FeatureContext 中获取标签

javascript - Jasmine $location 测试