While you are working with selenium for automation testing, you may have experienced that some web controls do not respond well to selenium commands.Selenium drag and drop functions are such commands which do not work as expected.As solution we can automate drag and drop function using jQuery.simulate plugin.Following steps explain you how to use jQuery.simulate plugin and execute simple drag and drop code.
- First open visual studio IDE and create new unit test project.
- Then Install following NuGet Packages required for selenium automation.
- Selenium.Support
- Selenium.WebDriver
- Selenium.WebDriver.IEDriver
- Next Add jQuery.simulate plugin using NuGet package manager.
- After add this plugin, You can find newly created Scripts folder in solution explorer and inside that folder you can find jquery.simulate.js file.
- Now you can try following simple code.
- Inside test method, it navigate to "https://jqueryui.com/droppable/" page and call DragAndDrop method with webdriver instance,drag element id and drop element id as parameters.
- Inside DragAndDrop method,.
- First get content of jquery.simulate.js file into jsFile variable.
- Then execute jsFile and trigger_drop() javascript function using javascriptexecutor interface.
- trigger_drop() function can be explained as follows.
- First create draggable and droppable varables.
- Then create droppableOffset variable and assign value of drop area offset.
- Next create draggableOffset variable and assign values of drag element offset.
- Then find values for dx and dy which give how much distance element need to be dragged.
- Then call simulate function to drag and drop the element.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System.IO;
namespace TestDragDrop
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
IWebDriver driver = new InternetExplorerDriver();
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 0, 60));
driver.Navigate().GoToUrl("https://jqueryui.com/droppable/");
driver.SwitchTo().Frame(0);
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("draggable")));
DragAndDrop(driver, "draggable", "droppable");
}
public static void DragAndDrop(IWebDriver driver, string draggerID, string dropID)/*Drag and Drop*/
{
var jsFile = File.ReadAllText(@"F:\Hbackup\SerealizeTest\TestDragDrop\TestDragDrop\Scripts\jQuery.Simulate\" + "jquery.simulate.js");
var js = driver as IJavaScriptExecutor;
js.ExecuteScript(jsFile + "function trigger_drop() {draggable = $('#" + draggerID + "'); droppable = $('#" + dropID + "');droppableOffset = droppable.offset(); draggableOffset = draggable.offset(); dx = droppableOffset.left - draggableOffset.left; dy = droppableOffset.top - draggableOffset.top; draggable.simulate('drag', { dx: dx,dy: dy }); }trigger_drop();");
}
}
}
No comments:
Post a Comment