I recently ran into an interesting challenge in QTP. I am scripting out a page that uses Javascript to make some controls invisible based on values selected in other controls. For example, if Field1 is selected to specific value, javascript runs something like this:
document.getElementById("Field2").style.display = "none"
Or
document.get\ElementById("Field2").style.visibility="hidden"
Interestingly, QTP doesn't recognize that anything has changed; it sees the visible/non-visible objects as completely the same. Coding for this behaviour becomes a bit problematic if QTP can't see it.
Now, realizing I set the datavalue for the test in Field1 to a known value, I *could* evaluate my data and determine if the control should show or not (and I might for a test case), but for most use, it is better to ask the object itself what its status is. This is because code changes could be made. We could add new values to Field1 that behaves the same way as the existing values. If this happens, my script breaks and requires maintenance. It makes much better sense to code my script to handle this independent of the data (components should, to the greatest extent practicable, be data-agnostic).
There is another interesting twist because it isn't actually Field2 (which is a <select> element) that is changed, but rather the <span> element in which is sits. How did I know which one to use? Simple. I viewed the HTML for the page, and checked the OnChange event of the control that controls the visibility of Field2. That told me exactly what to do. In my example, I included a line that shows how I'd grab Field2 itself if I wanted to do so.
So, I threw in some code to deal with this situation:
Dim objDoc
Dim objElement
Set objDoc = Browser("myBrow").Page("myPage").Object
'Set objElement = objDoc.GetElementByID("Field2")
Set objElement = objDoc.GetElementByID("spnField2")
If Not objElement is Nothing Then
If UCase(objElement.style.display) <> "NONE" Then
.WebList.Select DataTable.Value("Field2", dtLocalSheet)
End If
Else
Reporter.ReportEvent micWarning, "DataEntry", "Field2 control not found; procceding"
End If
Set objElement = Nothing
Set objDoc = Nothing
I also added some code to move forward if it isn't found, and just note the event.
Some folks I have worked with in the past have said that using solutions outside of the tool is bad, but this solution works very well, is very self-documenting, and relies on technology outside of QTP. No offense intended to Hp (and MIC that was), but sometimes, the best tool isn't the tool. If you can't seem to make QTP do what you want, don't forget the power of the HTML DOM.
posted @ Thursday, May 01, 2008 9:31 AM