-->

Protractor how to test select2

2019-02-15 14:33发布

问题:

I have a select2 drop-down where you need to first enter 2 characters and then select your item. I am unable to test this with Protractor.

var select2 = element(by.css('div#s2id_person'));
select2.click();
select2.sendKeys('ip');
select2.sendKeys(protractor.Key.ENTER);

The following gets an error about being unable to focus the element when you try to sendKeys.

回答1:

The following snippet successfully activates and selects the first option in a select2 widget, it allows for loading options over a network.

There are several issues with the 'select2' widget - in regard to protractor E2E testing - which this snippet addresses. The comments explains it all very well.

/**
 * @param {string} select2Locator // CSS selector of select2 container
 * @param {string} opt_query // an optional Query string
 */
function select2First(select2Locator, opt_query){
    // the 'a' element inside the select2 will receive the 'mousedown' event
    var selector = select2Locator + ' a.select2-choice';
    // Locator for the select2 options
    var options = element.all(by.css('.select2-results-dept-0'));

    // select2 doesn't activate on click 
    // and protractor doesn't have a direct mousedown method on 'ElementFinder'.
    browser.driver.executeScript('$(arguments["0"]).mousedown();', (selector));

    if(opt_query){
        browser.driver.switchTo().activeElement().sendKeys(opt_query);
        // select2 can fetch options from over a network
        // so we confirm that all pending network requests are resolved after typing the query
        browser.driver.wait(function(){
            return browser.driver.executeScript('return $.active === 0;');
        }, 2000);
    }

    // makes sure all the options are rendered
    browser.driver.wait(function(){
        return options.count().then(function(count){
            return 0 < count;
        });
    }, 2000);

    options.first().click();
};

In your provided scenario, you would use it like this:

select2First('div#s2id_person', 'ip');