javascriptseleniumselenium-webdriversvgnightwatch.js

Workaround for Drag and Drop SVG elements in Chrome using Selenium?


Details:

"chromedriver": "^87.0.7",
"geckodriver": "^1.22.1",
"html-dnd": "^1.2.1",
"nightwatch": "^1.5.1",

Expected

Drag and drop an SVG element to other SVG element using Nightwatch framework in JavaScript.

Actual

Test passes but no actual movement has occurred.

Description I have tried using the following:

browser.moveToElement(locator, dragElement, 1, 1);
browser.mouseButtonDown(0);
browser.moveToElement(locator, dropElement, 1, 1);
browser.mouseButtonUp(0);

I noticed moving the mouse while the test was running would allow the drag and drop to work on SVG elements.

Used html-dnd and nothing.

const dragAndDrop = require('html-dnd').codeForSelectors;

"Drag and Drop": function (browser) {
        browser.url(myurl);
        browser.useXpath();
        browser.execute(dragAndDrop, [svgDragElement, svgDropElement]);
        browser.end();
    }

Solution

  • Edit:
    If the code snippet below doesn't work, on the second moveToElement() change the pixels in X and y axis

    Ok so with a lot of trial and error plus help from fellow Automation engineers I found the solution.

    browser.moveToElement(locator, dragElement, 1, 1);
    browser.mouseButtonDown(0);
    browser.moveToElement(locator, dragElement, 1, 1);    // yes, move to your starting 
    browser.moveToElement(locator, dropElement, 1, 1);    // element again
    browser.mouseButtonUp(0);    
    

    can't explain this weird behavior but my guess it gets the "focus" on the element which is necessary for the method to work.

    NOTE
    In some cases browser.pause() will be necessary between moveToElement()