Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behat/Mink and Select2 combo

I try to create a Behat scenario with web UI using Select2.

When I try to change the select value, I've an Behat error because of the base select which is hide by Select2.

But I already have an error with the select2 component because mink can not interact with it.

Have you already use Behat/Mink with Select2 ? Have you tips to help me ?

like image 836
Jérémy Avatar asked Jan 23 '26 11:01

Jérémy


1 Answers

I finally write a Behat to interact with Select2 field like a user can do.

Here an extract of the most complete step :

/**
 * @When /^(?:|I )fill in select2 input "(?P<field>(?:[^"]|\\")*)" with "(?P<value>(?:[^"]|\\")*)" and select "(?P<entry>(?:[^"]|\\")*)"$/
 */
public function iFillInSelectInputWithAndSelect($field, $value, $entry)
{
    $page = $this->getSession()->getPage();

    $inputField = $page->find('css', $field);
    if (!$inputField) {
        throw new \Exception('No field found');
    }

    $choice = $inputField->getParent()->find('css', '.select2-selection');
    if (!$choice) {
        throw new \Exception('No select2 choice found');
    }
    $choice->press();

    $select2Input = $page->find('css', '.select2-search__field');
    if (!$select2Input) {
        throw new \Exception('No input found');
    }
    $select2Input->setValue($value);

    $this->getSession()->wait(1000);

    $chosenResults = $page->findAll('css', '.select2-results li');
    foreach ($chosenResults as $result) {
        if ($result->getText() == $entry) {
            $result->click();
            break;
        }
    }
}

I'm going to Open Source Select2 contexts in a few days on Github.

like image 93
Jérémy Avatar answered Jan 26 '26 03:01

Jérémy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!