Skip to content

Instantly share code, notes, and snippets.

@IslandUsurper
Created March 10, 2015 18:50
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IslandUsurper/12723643dddc9315ff71 to your computer and use it in GitHub Desktop.
Save IslandUsurper/12723643dddc9315ff71 to your computer and use it in GitHub Desktop.
Behat Step to select an autocomplete suggestion
<?php
use Behat\Mink\Extension\ElementNotFoundException;
use Drupal\DrupalExtension\Context\DrupalContext;
class FeatureContext extends DrupalContext {
/**
* @When I select the first autocomplete option for :prefix on the :field field
*/
public function iSelectFirstAutocomplete($prefix, $field) {
$field = $this->fixStepArgument($field);
$session = $this->getSession();
$page = $session->getPage();
$element = $page->findField($field);
if (!$element) {
throw new ElementNotFoundException($session, NULL, 'named', $field);
}
$page->fillField($field, $prefix);
$xpath = $element->getXpath();
$driver = $session->getDriver();
$prefix = $this->fixStepArgument($prefix);
$chars = str_split($prefix);
$last_char = array_pop($chars);
// autocomplete.js uses key down/up events directly.
$driver->keyDown($xpath, 8);
$driver->keyUp($xpath, 8);
$driver->keyDown($xpath, $last_char);
$driver->keyUp($xpath, $last_char);
// Wait for AJAX to finish.
$this->getSession()->wait(500, '(typeof(jQuery)=="undefined" || (0 === jQuery.active && 0 === jQuery(\':animated\').length))');
// Press the down arrow to select the first option.
$driver->keyDown($xpath, 40);
$driver->keyUp($xpath, 40);
// Press the Enter key to confirm selection, copying the value into the field.
$driver->keyDown($xpath, 13);
$driver->keyUp($xpath, 13);
// Wait for AJAX to finish.
$this->getSession()->wait(500, '(typeof(jQuery)=="undefined" || (0 === jQuery.active && 0 === jQuery(\':animated\').length))');
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment