Thursday, March 31, 2011

Selenium: How do I use javascript to clear a value from a form field?

I'm using the selenium IDE and the Selenium-Fitnesse Bridge fixture and I'm trying to test that when I clear a default value out of a form field, my form displays an error message.

So when I record with the Selenium IDE, what it does is the equivalent of telling Selenium to type nothing.

| type | text_field |  |

The problem with this is that the Fitnesse fixture I'm using expects that second argument to not be null.

Is there a way in Selenium to "clear a value" rather than "typing nothing"?

From stackoverflow
  • You can do it via javascript as such:

    | verifyEval | javascript{this.browserbot.getCurrentWindow().document.getElementById('CONTROL_ID').value = ''} ||
    

    Effectively the verifyEval statement allows you to execute any piece of javascript that you'd like. Makes some difficult problems to accomplish with Selenium much simpler.

    I used this tutorial (today believe it or not) to figure things out.

    Andrew : This actually doesn't work. Also, to run our javascript, we would need to use runScript instead of verifyEval, but I think something along these lines might work. Not sure why the above code does not work though.
    Gavin Miller : @Andrew - What specifically doesn't work? Throw up a little more detail and I'll revise my answer.
    Andrew : I'm getting this exception: java.lang.RuntimeException: this.browserbot.getCurrentWindow().document.getElementById('reg_start_date').value = '' was not found in captured value map
    Gavin Miller : So Andrew work backwards and find the problem. Use your js debug skills, and see what isn't being returned properly and then work forward from there. The javascript is evaluating, now it's your turn to work out how to apply it.
  • I used this to get it to work. reg_start_date is the id of my input field.

    | storeEval | window.document.getElementById('reg_start_date').value = '' |
    

    From the selenium reference:

    Note that, by default, the snippet will run in the context of the "selenium" object itself, so this will refer to the Selenium object. Use window to refer to the window of your application, e.g. window.document.getElementById('foo')

    Also, avoid wrapping the javascript code with javascript{}, it will not work.

  • We had this issue at the beginning as well. Try: | type | text_field | blank |

    Look for more info on the Fitnesse documentation for the use of blank and null.

    :)

0 comments:

Post a Comment