从预先填充的列表中选择一个选项的操作如下:
$selector = "select[name='tags']";
$this->tester->openSelect2($selector);
$this->tester->selectOptionForSelect2($selector, array('text' => $tag));
$this->tester->closeSelect2($selector);
找到了这个要点https://gist.github.com/tortuetorche/412fbac4f17db5e78e79。
问题是我的 select2 也有动态标签。 (https://select2.org/tagging)
有人知道如何使用 codeception 创建动态标签吗?谢谢。
通常我使用
WebDriver Keys
类来测试动态 select2 字段。// Fill your dynamic tag with the option you want to search
$I->fillField($selector, 'Orang');
// Then, wait for the option is loaded
$I->waitForText('Orange', 30);
// Finaly, use WebDriverKeys to select the option
$I->pressKey($selector, \Facebook\WebDriver\WebDriverKeys::ENTER);
选择多个选项也很有效。
我有同样的需求,根据@samuel的回答,我将以下方法添加到
tests/_support/AcceptanceTester.php
/**
* Fills a Select2 and click on the first matching element
* @param string $selector the id of the select element
* @param string $query the query to type in selector
* @param string $expeccted the expected text to see, by default the query
*/
public function fillSelect2($selector, $query, $expected = '')
{
// based on https://stackoverflow.com/a/69160282
if ($expected === '') {
$expected = $query;
}
$selector_name = str_replace('#', '', $selector);
$container_selector = '#select2-' . $selector_name . '-container';
$input_selector = 'input[aria-controls=select2-' . $selector_name . '-results]';
$this->waitForElementVisible($container_selector);
// Click using JS to avoid error click is intercepted
$this->click($container_selector);
// Fill your dynamic tag with the option you want to search
$this->fillField($input_selector, $query);
// Then, wait for the option is loaded
$this->waitForText($expected, 3);
// Finaly, use WebDriverKeys to select the option
$this->pressKey($input_selector, \Facebook\WebDriver\WebDriverKeys::ENTER);
}
然后在测试中我可以简单地右击
$I->fillSelect2('#some-selector-id', 'some text');
,测试将输入some text
并单击第一个结果