Search code examples
javascriptprotractorcucumbercucumberjs

browser.wait and conditions with Protractor


With protractor, I'm creating a customer object, and when saving I want to check that the customer object that just got created is actually displayed.

In "UI" term, after clicking on the save button there is a little delay where the dialog creation is closed and the customer list updated.

I have the original customerCount, so I want the browser to wait until there is customerCount + 1 customer card.

Here is my code :

Step :

When('I wait for the customer list to be updated', function() {
    return browser.wait(Utils.countElements('.tb-card-item', customerCount + 1), 5000);
});

countElements :

module.exports = {
    countElements(css, i) {
        let e = element.all(by.css(css));
        return e.count().then(function(elementCount) {
            console.log('COUNT : ' + elementCount);
            return elementCount === i;
        })
    }
};

My understanding was that the countElement function would be executed until it returns true, so until the number of customer is the right one. What happens in reality is that it gets executed once and goes straight to the next instruction, failing my tests.

Thanks in advance


Solution

  • browser.wait returns Promise object, according to official documentation. Basically, there are two options how you can tell cucumber that this particular step is async.

    First, if with done callback

    When('I wait for the customer list to be updated', function(done) {
        browser.wait(Utils.countElements('.tb-card-item', customerCount + 1), 5000)
           .then(() => {
                done();
           })
    })
    

    Second, with async keyword

    When('I wait for the customer list to be updated', async function() {
        await browser.wait(Utils.countElements('.tb-card-item', customerCount + 1), 5000);
    });
    

    But it is not enough just to return promise, like you did, cucumber has no idea how to deal with it. You have to tell cucumber that he can't move on, until this promise resolved.