Firing change events in Selenium and IEx?

2019-07-03 16:14发布

I'm just getting started on Selenium, so I'm still wrapping my head around all the moving parts. I've got my first test suite up and running, but can't for the life of me get jQuery event listeners to fire in IE.

This is especially problematic on dynamic AJAX dropdowns such as $('#country').live('change',showStates) select -> id=country | label=United States

The selenium driver triggers the events in response to the test script for all other browsers, but nothing I've tried causes or forces the change event to fire. I've tried using every method I could find documented on SO, including:

None of these commands fire the event in IE9, 8 (emulated) or 7 (emulated). FWIW It's unclear if these actually cause the event to fire in other browsers as the other browsers fire the change event without an additional call. I'm running the standalone selenium jar 2.33 on Windows 7.

How do I fire change events in IE with selenium?

2条回答
萌系小妹纸
2楼-- · 2019-07-03 16:27

From my experience triggering javascript/jQuery directly is not the safest way to go about things. Instead try use UI interactions to simulate a user. For example to trigger the 'country.change()' event, just change the country in the country field using Selenium (you may have to tab out of the field). I believe this is the intended use.

I have found some Drop-down Lists can be painful. I would try the following set of actions on your Drop-down List:

  1. Get the currently selected option (call a getText on the topmost element of the DDL)
  2. Click the DDL (to display the options
  3. Get a list of displayed options
  4. Discover the distance between the current option and the intended
  5. Send the appropriate number of DOWN or UP keys (depending on direction) followed by a ENTER or TAB key

I have had to follow this sort of process when working with a third party UI package that formats the DDL separately from where it handles the manipulation of the DDL. This means when Selenium is interacting with the element it is use to the intended effects do not occur because they are being handled elsewhere by javascript that is not with in the context of the element Selenium has the handle of. Sending keys mimics a users actions and forces the javascript to execute itself. Let me know if this is unclear and whether it works.

查看更多
ら.Afraid
3楼-- · 2019-07-03 16:54

Fire the change event by performing the actions that would trigger it. That is a fundamental part of the WebDriver philosophy.

If your dropdown is implemented with standard <select> and <option> tags, you can use the Select utility class.

WebElement country = driver.findElement(By.id("country"));
Select selector = new Select(country);
selector.selectByVisibleText("Lithuania");

This won't trigger a change unless the new option is different, saving you some conditional logic as well.

查看更多
登录 后发表回答