Search code examples
javaselenium-webdrivergroovyautomated-testskatalon-studio

How to convert WebElement to TestObject in katalon studio?


I have WebElement which I have to convert into Testobject in katalon using groovy script.

For Example

List<WebElement> WEs = WebUI.executeJavaScript("return document.querySelector('#email').parentElement", [])

Now I want to convert WEs[0] to TestObject which Katalon accepts.

Please let me know if you have an idea about this.


Solution

  • To create Test Object from any WebElement, I have developed the function as below

    public static String WebElementXPath(WebElement element) {
        if (element.tagName.toUpperCase() == 'HTML')    return '/html';
        if (element.tagName.toUpperCase() == 'BODY')      return '/html/body';
    
    
        // calculate position among siblings
        int position = 0;
        // Gets all siblings of that element.
        List<WebElement> siblings = WebUI.executeJavaScript("return arguments[0].parentNode.childNodes", [element])
        WebElement innerSibs
        //List<WebElement> siblings = element.parentNode.childNodes;
    
        WebElement sibling
        def type,response
        for(int i=0;i<siblings.size();i++){
            type = WebUI.executeJavaScript("return arguments[0].nodeType", [siblings[i]])
            if (type == null){
                continue;
            }
            if(type!=1){
                continue;
            }
            sibling = siblings[i];
            // Check Siblink with our element if match then recursively call for its parent element.
            if (sibling == element) {
                innerSibs = WebUI.executeJavaScript("return arguments[0].parentElement", Arrays.asList(sibling))
                if(innerSibs==null){
                    return ""
                }
                response = functions.WebElementXPath(innerSibs)
                return response+'/'+element.tagName+'['+(position+1)+']';
    
            }
    
            // if it is a siblink & element-node then only increments position.
            type = WebUI.executeJavaScript("return arguments[0].nodeType", [sibling])
            if (type == 1 && sibling.tagName == element.tagName)            position++;
    
        }
    }
    

    And then I have created function to get test object as below as suggested by Mate Mrše

    public static TestObject getTestObjectFromWebElement(WebElement element) {
        TestObject object = new TestObject()
        object.addProperty("xpath", ConditionType.CONTAINS, functions.WebElementXPath(element))
        return object
    }
    

    Note : "Framework" folder had been created by us as inside the Keyword folder and then We had created the "functions" keyword

    enter image description here

    I hope this might help other developers.