Search code examples
seleniumselenium-webdrivergroovygeb

How to clear the field of web element - Groovy


According to chapter 4.10 of this documentation:

To clear the field of webElement I can do:

webElement << Keys.chord(Keys.CONTROL, "a", Keys.BACK_SPACE)

But it doesn't look clean for me. Is there a way to write a method named "clear" which could be called on a webElement and invokation of this method would look like this?

webElement.clear()

How this method would look then?

I managed just to do something like this:

def clear() {
    return Keys.chord(Keys.CONTROL, "a", Keys.BACK_SPACE)
}

webElement << clear()

Do I have other possibilities or approaches to this problem to be able to call a method on element to clear it?

I can not use the selenium method clear() cause the spark framework which supports application which I test forbid this method.


Solution

  • The easiest way to clear an element in Geb is to simply set it’s value to an empty string:

    $(“input”).value(“”)
    

    That will call WebElement’s clear() method so if that’s not an option and you would actually want to perform the key press combination as in your question then you have two options. My preferred one would be to write a module with a clear() method:

    class ManuallyCleared extends Module {
        void clear() {
             leftShift Keys.chord(Keys.CONTROL, “a”, Keys.SPACE)
        }
    }
    

    And the use it like:

    $(“input”).module(ManuallyCleared).clear()
    

    Another option would be to implement a custom navigator and add the clear() method there.