11

In previous questions I have seen that a nice way to wait for the url to change is to use:

browser.wait( function() {
    return browser.getCurrentUrl().then(function(url) {
        return /myURL/.test(url);
    });
}, 10000, "url has not changed");`

But I am trying to have a method that I can pass myURL as a variable (in case I need to use it with other sites) and is not working.

I am trying this in my Page Object file:

this.waitUrl = function(myUrl) {
    browser.wait( function(myUrl) {
        return browser.getCurrentUrl().then(function(url, myUrl) {
            return myUrl.test(url);
        });
    }, 10000, "url has not changed");
};

Any ideas if this is even possible and how to do it if so?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
James Be
  • 125
  • 1
  • 1
  • 6

2 Answers2

12

Update (July 2016): with Protractor 4.0.0 you can solve it with urlIs and urlContains built-in Expected Conditions.


Original answer:

Don't pass myUrl inside the then function, it is available from the page object function scope:

browser.wait(function() {
    return browser.getCurrentUrl().then(function(url) {
        return myUrl.test(url);
    });
}, 10000, "url has not changed");

I would though define it as an Expected Condition:

function waitUrl (myUrl) {
    return function () {
        return browser.getCurrentUrl().then(function(url) {
            return myUrl.test(url);
        });
    }
}

So that you can then use it this way:

browser.wait(waitUrl(/my\.url/), 5000);
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Hi, thanks for the response. Tried both and got this: `Message: TypeError: myUrl.test is not a function Stacktrace: TypeError: myUrl.test is not a function at` – James Be Dec 21 '15 at 16:47
  • @JamesBe ah, sure, you are using the regular expression match, so your url passed into the expected condition has to be a regular expression. Updated the answer. – alecxe Dec 21 '15 at 17:03
  • @JamesBe you can also pass in a string and make a regular expression object via `new Regexp(myUrl)`. – alecxe Dec 21 '15 at 17:03
  • Legend! Thanks alecxe! – James Be Dec 22 '15 at 10:21
  • instead of "myUrl.test(url)" you can include anything that resolves to true when myUrl and url match, such as myUrl.include(url) – emery Mar 21 '19 at 20:58
6

For those that want an example for Protractor 4.0.0 through 5.3.0

You can use "ExpectedConditions" like so...

var expectedCondition = protractor.ExpectedConditions;
// Waits for the URL to contain 'login page'.
browser.wait(expectedCondition.urlContains('app/pages/login'), 5000);

If you want to validate this with an e2e test.

it('should go to login page', function() {
    loginPage.login();
    const EC = protractor.ExpectedConditions;

    browser.wait(EC.urlContains('app/pages/login'), 5000).then(function(result) {
        expect(result).toEqual(true);
    });

});
Rahul Singh Chandrabhan
  • 2,531
  • 5
  • 22
  • 33
Rmalmoe
  • 993
  • 11
  • 13