WatIn Add a new option to a Selectlist?

对着背影说爱祢 提交于 2019-12-11 17:34:12

问题


I need to add a new option to a selectList in one of my unit tests, and I can't figure out how to do it.

The Dropdown currently has 2 options, I want to add a third, and use it.

I tried to use JavaScript injection using http://stevenharman.net/blog/archive/2007/07/10/add-option-elements-to-a-select-list-with-javascript.aspx as a base, but that failed. I get exceptions that crash the IE browser every time, and the text "RunScript failed" gets printed into my logs even though I don't use that text in my error output.

Is this possible in Watin? Or has Open Source Failed me?


回答1:


Using the code in the link you provided, with one small change I've gotten it to work.

My changes

  • Changed the ID to the ID of my dropdown (of course!)
  • Changed the $ in the element get to 'document.getElementById'. With the $ in there instead I don't see any obvious errors or anything like that; just no action taken.

The 'New Option' is added to the dropdown as the last item and it is the selected item.

string js = "";
js = js + "var theSelectList = document.getElementById('myDropDownID'); ";
js = js + " AddSelectOption(theSelectList, \"My Option\", \"123\", true);";
js = js + " function AddSelectOption(selectObj, text, value, isSelected) ";
js = js + "{";
js = js + " if (selectObj != null && selectObj.options != null)";
js = js + "{";
js = js + " selectObj.options[selectObj.options.length] = new Option(text, value, false, isSelected);";
js = js + "}}";

myIE.Document.Eval(js);

My setup

  • WatiN 2.0
  • IE8
  • Win7

Checked when the dropdown has 1 entry and 2 entries; both scenarios had "My Option" added without issue.



来源:https://stackoverflow.com/questions/6392685/watin-add-a-new-option-to-a-selectlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!