You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Cypress模拟鼠标操作创建时间段失败,求解决方法

Cypress模拟鼠标拖动创建时间段的解决思路

问题背景

需通过Cypress模拟鼠标点击、按住拖动、释放的操作,选择多个小时块以创建时间段。使用Cypress 12.7版本,尝试通过trigger模拟mousedown/mousemove/mouseup事件,但未达到预期效果。

已尝试代码

cy.get(':nth-child(36) > .fc-timegrid-slot-lane')
  .trigger('mousedown', { which: 1, pageX: 684.625, pageY: 704.188 })
  .trigger('mousemove', { which: 1, pageX: 762.875, pageY: 782.438 })
  .trigger('mouseup')

可行解决思路

  • 使用Cypress 12+内置drag命令:原生拖拽命令更贴近真实用户操作,无需手动拼接多个鼠标事件,示例:

    cy.get(':nth-child(36) > .fc-timegrid-slot-lane')
      .drag(':nth-child(40) > .fc-timegrid-slot-lane', { force: true })
    

    force: true可忽略元素可见性或交互状态校验,适用于存在遮挡的场景。

  • 动态计算元素坐标:硬编码pageX/pageY易受页面布局变化影响,通过getBoundingClientRect()获取元素实时位置,计算中心坐标作为触发点:

    cy.get(':nth-child(36) > .fc-timegrid-slot-lane').then(startEl => {
      const startRect = startEl[0].getBoundingClientRect();
      cy.get(':nth-child(40) > .fc-timegrid-slot-lane').then(endEl => {
        const endRect = endEl[0].getBoundingClientRect();
        cy.get(':nth-child(36) > .fc-timegrid-slot-lane')
          .trigger('mousedown', { 
            which: 1, 
            clientX: startRect.left + startRect.width/2, 
            clientY: startRect.top + startRect.height/2 
          })
          .trigger('mousemove', { 
            which: 1, 
            clientX: endRect.left + endRect.width/2, 
            clientY: endRect.top + endRect.height/2 
          })
          .trigger('mouseup');
      });
    });
    
  • 补充前置事件与等待:针对FullCalendar(从类名fc-timegrid-slot-lane推测)这类组件,需确保元素渲染完成,并补充mouseover事件模拟真实操作流程:

    cy.get(':nth-child(36) > .fc-timegrid-slot-lane')
      .should('be.visible')
      .trigger('mouseover')
      .trigger('mousedown', { which: 1 })
      .trigger('mousemove', { toElement: cy.get(':nth-child(40) > .fc-timegrid-slot-lane'), which: 1 })
      .trigger('mouseup');
    
  • 切换事件监听目标:若组件在父容器而非单个时间块上监听鼠标事件,可定位到父容器(如.fc-timegrid-slots)触发事件:

    cy.get('.fc-timegrid-slots')
      .trigger('mousedown', { which: 1, pageX: startX, pageY: startY })
      .trigger('mousemove', { which: 1, pageX: endX, pageY: endY })
      .trigger('mouseup');
    
  • 启用实验性鼠标事件:在cypress.config.js中开启实验配置,提升事件模拟真实性:

    module.exports = defineConfig({
      e2e: {
        experimentalMouseEvents: true,
      },
    });
    

内容的提问来源于stack exchange,提问作者Janko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 03:52:47