Cypress.io 测试中没有发生拖放

Drag and drop is not happening in Cypress.io test

我正在尝试拖动一个元素,然后将其放入拖放区,但测试未在 Cypress.io 中执行拖放操作。如果有人可以就此处的潜在问题提出建议,那将非常有帮助。没有抛出错误,但是这里没有发生拖放。

describe('Verify the drag and drop test', function() {

  it.only('Check whether the drag and drop of an item is working fine', function() {

  cy.visit('http://www.seleniumeasy.com/test/drag-and-drop-demo.html')  

    const MyDataTransfer = function () {};
    const dt = new MyDataTransfer ();
    dt.types = [];

    // cy.wait(3000);

    cy.get('#todrag span')
      .contains('Draggable 1')
      .trigger("draggable", {dataTransfer: dt});

    cy.get("#todrag span")
      .contains('Draggable 1')
      .trigger('mousedown', { which: 1, pageX: 600, pageY: 600 })
      .trigger('mousemove', { which: 1, clientX: 330, clientY: 35 });

    cy.wait(3000);

    cy.get('#mydropzone')
      .trigger("dropzone", {dataTransfer: dt});                     
  });   
});

一些更改应该可以实现您正在寻找的内容。以下是解决此问题所采取的步骤的细分...

首先,不要删除 MyDataTransfer,只需构建一个新的 DataTransfer 对象,它包含拖动事件所需的必要属性和方法:

const dataTransfer = new DataTransfer;

接下来最好触发native drop and drag events, as opposed to draggable and dropzone. Selenium Easy is listening for dragstart, dragend, and drop (you can see this inside of their drag-and-drop-demo.js source file)。将这些放在辅助函数中,稍后在测试中调用:

function dndIt() {
  cy.get('#todrag span:first-of-type')
    .trigger('dragstart', { dataTransfer });

  cy.get('#mydropzone')
    .trigger('drop', { dataTransfer });

  cy.get('#todrag span:first-of-type')
    .trigger('dragend');               // <-- seleniumeasy listens for this...
}                                      // otherwise, draggables are copied.    

一个beforeEach块有助于设置视口和访问应用程序:

beforeEach(function() {
  cy.viewport(1000, 600);
  cy.visit('https://www.seleniumeasy.com/test/drag-and-drop-demo.html');
});

最后,测试块调用辅助函数,并断言该项目已被拖放:

it('Check whether the drag and drop of an item is working fine', function() {
  dndIt();

  cy.get('#droppedlist')
    .should(($el) => {
      expect($el.children()).to.have.lengthOf(1)
    });
});

完整的解决方案如下:

describe('Verify the drag and drop test', function() {
  const dataTransfer = new DataTransfer;

  function dndIt() {
    cy.get('#todrag span:first-of-type')
      .trigger('dragstart', { dataTransfer });

    cy.get('#mydropzone')
      .trigger('drop', { dataTransfer });

    cy.get('#todrag span:first-of-type')
      .trigger('dragend');               // <-- seleniumeasy listens for this...
  }                                      // if left out, draggables are copied.

  beforeEach(function() {
    cy.viewport(1000, 600);
    cy.visit('https://www.seleniumeasy.com/test/drag-and-drop-demo.html');
  });

  it('Check whether the drag and drop of an item is working fine', function() {
    dndIt();

    cy.get('#droppedlist')
      .should(($el) => {
        expect($el.children()).to.have.lengthOf(1)
      });
  });
});

drag_n_drop_spec.js provided in the cypress-example-recipes repo 是有用的资源。