d_z90
d_z90

Reputation: 1263

Creating some tests for an ionic app with protractor to test if the user can successfully drag and drop an element on chrome

I am creating some tests for an ionic app with protractor to test if the user can successfully drag and drop an element on chrome. I have tried first with mouseDown(), mouseMove() and mouseUp(), like in the following case:

it ('should destroy card after swipe', function() {
    var card1Move = {x: 200, y: 0};

    browser.actions()
        .mouseMove(card1)
        .mouseDown()
        .mouseMove(card1Move)
        .mouseUp()
        .perform();

    browser.sleep(500);
    expect(card1.isPresent()).toBeFalsy();
});

But it didn't work. Then I have tried with in-built dragAndDrop() method, like this:

it ('should destroy card after swipe', function() {
    var card1Move = {x: 200, y: 0};

    browser.actions()
        .dragAndDrop(card1, card1Move)
        .mouseUp()
        .perform();

    browser.sleep(500);
    expect(card1.isPresent()).toBeFalsy();
});

But it didn't work either. Do you know what is the issue with my code? Thanks in advance for your replies!

Upvotes: 1

Views: 104

Answers (1)

Florent B.
Florent B.

Reputation: 42518

If the drag and drop is an HTML5 implementation, then your best chance is probably to simulate the events with executeScript :

browser.executeScript(dragAndDrop, card1.getWebElement(), 200, 0);
var dragAndDrop = function(source, offsetX, offsetY){      
  var rect = source.getBoundingClientRect();
  var dragPt = {x: rect.left + (rect.width >> 1), y: rect.top + (rect.height >> 1)};
  var dropPt = {x: dragPt.x + offsetX, y: dragPt.y + offsetY};
  var target = source.ownerDocument.elementFromPoint(dropPt.x, dropPt.y);
  var dataTransfer = {
    items: {},
    types: [],
    files: [],
    setData: function (format, data) {
      this.items[format] = data;
      this.types.push(format);
    },
    getData: function (format) { return this.items[format]; },
    clearData: function (format) { delete this.items[format]; }
  };

  emit(source, 'mouseover mouseenter mousedown dragstart dragenter drag dragover dragleave', dragPt);
  emit(target, 'dragenter dragover drop', dropPt);
  emit(source, 'dragend', dropPt);

  function emit (element, events, pt, data) {
    events.split(' ').forEach(function(event){
      var evt = source.ownerDocument.createEvent('MouseEvent');
      evt.initMouseEvent(event, !0, !0, window, 0, 0, 0, pt.x, pt.y, !1, !1, !1, !1, 0, null);
      if (/^drag|^drop/.test(event)) evt.dataTransfer = dataTransfer;
      element.dispatchEvent(evt);
    });
  };
};

Upvotes: 1

Related Questions