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

如何使用Cypress插件实现拖拽自动化?无法将首个任务拖至第三个任务

Cypress拖拽任务自动化失败的解决方案
  • 上下文丢失问题:你在.each()回调里使用cy.get()会全局查找元素,而非在包含"Hamza Malik"的目标列内定位任务,这会导致选中错误元素或其他列的任务。

修正代码,通过cy.wrap($column)结合.find()限定查找范围,确保操作目标列内的任务:

cy.get('div[data-columns="columns"]')
  .find('div[data-columnContainer="columnContainer"]')
  .each(($column) => {
    if ($column.text().includes("Hamza Malik")) {
      cy.wrap($column)
        .find('div[data-taskDraggable="taskDraggable"]:nth-child(1)')
        .drag(
          cy.wrap($column).find('div[data-taskDraggable="taskDraggable"]:nth-child(3)'),
          { force: true }
        );
    }
  });
  • 拖拽插件兼容性检查:若使用@4tw/cypress-drag-drop插件,需确认安装和导入步骤正确:

    • 安装命令:npm install @4tw/cypress-drag-drop --save-dev
    • 在cypress/support/e2e.js中导入:require('@4tw/cypress-drag-drop')
  • 原生事件模拟备选方案:如果插件拖拽仍失效,可用Cypress原生事件模拟完整拖拽流程:

cy.get('div[data-columns="columns"]')
  .find('div[data-columnContainer="columnContainer"]')
  .each(($column) => {
    if ($column.text().includes("Hamza Malik")) {
      const $source = $column.querySelector('div[data-taskDraggable="taskDraggable"]:nth-child(1)');
      const $target = $column.querySelector('div[data-taskDraggable="taskDraggable"]:nth-child(3)');

      cy.wrap($source)
        .trigger('mousedown', { button: 0 })
        .trigger('mousemove', { 
          clientX: $target.getBoundingClientRect().x + 50, 
          clientY: $target.getBoundingClientRect().y + 20 
        })
        .trigger('mouseup', { force: true });
    }
  });
  • 定位准确性验证:可添加断言或日志确认元素定位是否正确:
cy.wrap($column)
  .find('div[data-taskDraggable="taskDraggable"]:nth-child(1)')
  .should('be.visible')
  .invoke('text')
  .then(text => console.log('源任务:', text));

cy.wrap($column)
  .find('div[data-taskDraggable="taskDraggable"]:nth-child(3)')
  .should('be.visible')
  .invoke('text')
  .then(text => console.log('目标任务:', text));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:22:13