In order to implement drag and drop for Selenium tests, I referred to http://elementalselenium.com/tips/39-drag-and-drop There it's mentioned to use javascript(from https://gist.github.com/rcorreia/2362544) to handle drag and drop.
I implemented it as it is and it worked. But in my case, I've dynamic xpaths for source and target element. In order to achieve that, I tried with following code:
package org.test.selenium;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class HTML5DragAndDrop {
WebDriver driver = null;
@BeforeClass
public void setUp(){
System.out.println(System.getProperty("user.dir"));
String chromeDriver = System.getProperty("user.dir")+ File.separator + "drivers" + File.separator + "chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromeDriver);
driver = new ChromeDriver();
driver.get("http://the-internet.herokuapp.com/drag_and_drop");
}
@AfterClass
public void tearDown(){
driver.quit();
}
@Test
public void testDragAndDrop() throws IOException, InterruptedException {
String filePath = "C://dnd.js";
String source = "//div[@id='column-a']";
String target = "//div[@id='column-b']";
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine())!=null)
buffer.append(line);
String javaScript = buffer.toString();
javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
}
}
but it gives error:
org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected identifier
(Session info: chrome=35.0.1916.153)
However, if use source and target as css like following, it works perfectly fine:
String source = "#column-a";
String target = "#column-b";
Can someone please suggest me changes that need to be done so that above will work with source and target elements with xpaths? In my case, I'm constrained to use xpath that's I've to do this with xpath only.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…