进行一些更改应该可以实现您想要的效果。以下是解决此问题所采取的步骤的详细说明......
首先,而不是存根MyDataTransfer
,只需构造一个新的数据传输 https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/DataTransfer对象,其中包含拖动事件所需的必要属性和方法:
const dataTransfer = new DataTransfer;
接下来最好触发本机放置和拖动事件 https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API#Drag_Events,相对于draggable
and dropzone
。 Selenium Easy 正在监听dragstart
, dragend
, and drop
(你可以在他们的内部看到这个Drag-and-drop-demo.js 源文件 https://www.seleniumeasy.com/test/js/drag-and-drop-demo.js)。将它们放入辅助函数中,稍后在测试中调用:
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.
A beforeEach
block 对于设置视口和访问应用程序很有帮助:
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)
});
});
});
The Drag_n_drop_spec.js https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/testing-dom__drag-drop/cypress/integration/drag_n_drop_spec.js中提供的cypress-example-recipes 仓库 https://github.com/cypress-io/cypress-example-recipes是一个有用的资源。