Reputation: 1506
I want to test with Behat a select2 dropbox that makes an ajax call in order to get the results. The problem is that immediately after I populate the search box of select2 the dropdown closes immediately so the search is not happening.
If the select is already populated (a normal dropdown with predefined values) everything is ok because all the data is there and it takes it right away.
I'm using Behat Page object
for my project so here is my method:
select2FieldPopulate
public function select2FieldPopulate($field, $value)
{
$select2Field = $this->find('css', '.'.$field);
//check if select2Field exists
if (!$select2Field) {
throw new \Exception(sprintf("Field %s was not found", $field));
}
$select2Field->click();
$select2Input = $this->find('css', '.select2-drop.select2-drop-active .select2-search input.select2-input');
if (!$select2Input) {
throw new \Exception(sprintf("Field %s was not found", "select2-input"));
}
$select2Input->setValue($value);
}
js
function buildSelect2Element(selector, placeholder, url) {
var element = $(selector).select2({
placeholder: placeholder,
minimumInputLength: 3,
ajax: {
url: url,
dataType: 'json',
data: function (term) {
return {
q: term
}
},
results: function (data) {
//workarround to fix select2
var results = [];
$.each(data, function (index, item) {
results.push({
id: item.id,
text: item.name
});
});
return {
results
}
}
}
});
return element;
}
On $select2Input->setValue()
the search box gets populated with the value but the search does not happen because the dropdown closes right away.
So the question is: Is there a way to force the box to stay open until the results are displayed (the ajax call is finished)?
Upvotes: 0
Views: 379
Reputation: 1506
I managed to make it work under select2 v4.x.
I added to the js the option to select on close like this:
js
function buildSelect2Element(selector, placeholder, url) {
var element = $(selector).select2({
theme: "classic",
placeholder: placeholder,
minimumInputLength: 3,
selectOnClose: true, //HERE
Then in my tests i used the evaluateScript method:
select2FieldPopulate method
$this->getDriver()->evaluateScript("$('#your_select2_element').select2('open')");
$this->getDriver()->evaluateScript("$('.select2-search__field').val('". $value ."').keyup();");
$this->getDriver()->evaluateScript("$('#your_select2_element').select2('close')");
Upvotes: 1