Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save swichers/13f24de9a56b50307956365a5a52d207 to your computer and use it in GitHub Desktop.
Save swichers/13f24de9a56b50307956365a5a52d207 to your computer and use it in GitHub Desktop.
Behat Step to select the first autocomplete suggestion
<?php
use Behat\Mink\Extension\ElementNotFoundException;
use Drupal\DrupalExtension\Context\DrupalContext;
class FeatureContext extends DrupalContext {
/**
* Gives us acess to the other contexts so we can access their properties.
*
* @BeforeScenario
*/
public function gatherContexts(BeforeScenarioScope $scope) {
$environment = $scope->getEnvironment();
$this->contexts['drupal'] = $environment->getContext('Drupal\DrupalExtension\Context\DrupalContext');
$this->contexts['mink'] = $environment->getContext('Drupal\DrupalExtension\Context\MinkContext');
}
/**
* @When I select the first autocomplete option for :prefix on the :field field
*/
public function iSelectFirstAutocomplete($prefix, $field) {
$session = $this->getSession();
$element = $session->getPage()->findField($field);
if (empty($element)) {
throw new ElementNotFoundException($session, NULL, 'named', $field);
}
$element->setValue($prefix);
$element->focus();
$xpath = $element->getXpath();
$driver = $session->getDriver();
// autocomplete.js uses key down/up events directly.
// Press the down arrow to open the autocomplete options.
$driver->keyDown($xpath, 40);
$driver->keyUp($xpath, 40);
$this->contexts['mink']->iWaitForAjaxToFinish();
// 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);
$this->contexts['mink']->iWaitForAjaxToFinish();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment