how can I get the current url using protractor?
Asked Answered
L

3

38

I am testing a website using protractor, and jasmine. I would like to know the current url in order to verify a test.

I have tried

function waitForUrlToChangeTo(urlRegex) {
    var currentUrl;

    return browser.getCurrentUrl().then(function storeCurrentUrl(url) {
            currentUrl = url;
        }
    ).then(function waitForUrlToChangeTo() {
            return browser.wait(function waitForUrlToChangeTo() {
                return browser.getCurrentUrl().then(function compareCurrentUrl(url) {
                    return urlRegex.test(url);
                });
            });
        }
    );
}

and I am using this function in this way

it('should log', function() {
    //element(by.model('user.username')).sendKeys('asd');
    //element(by.model('user.password')).sendKeys('asd');
    element(by.linkText('Acceder')).click();
    waitForUrlToChangeTo("http://localhost:9000/#/solicitudes");
});
Landahl answered 1/4, 2015 at 18:9 Comment(0)
G
54

If you want to just check the current URL, then use browser.getCurrentUrl():

expect(browser.getCurrentUrl()).toEqual("expectedUrl");

But, if you need to wait until URL matches a certain value, see the next part of the answer.


Here is a working code based on the example provided by the author of the Expected Conditions:

var urlChanged = function(url) {
  return function () {
    return browser.getCurrentUrl().then(function(actualUrl) {
      return url != actualUrl;
    });
  };
};

Usage:

element(by.linkText('Acceder')).click();
browser.wait(urlChanged("http://localhost:9000/#/solicitudes"), 5000); 
Geodetic answered 1/4, 2015 at 18:24 Comment(0)
C
43

Alecxe your answer was very helpful.

But couldn't you just code:

 expect(browser.getCurrentUrl()).toEqual('whateverbrowseryouarexpectingtobein');

And if this fails, then you know you're going to the wrong place.

Concord answered 8/7, 2015 at 15:50 Comment(2)
I think the purpose was to wait until the URL matched a certain value, not just to get the value at the given point in time.Sarabia
+1 to this answer. The question is "how can I get the current url using protractor?". This is the first google result. I think this answer is more helpful even if it doesn't apply to OP.Longsome
P
10

Since Protractor 4.0.0 you can now use expected conditions to know when your url changed.

const EC = protractor.ExpectedConditions;
browser.wait(EC.urlContains('my-url'), 5000);

The asnwer I found comes from this one, I have no real credits for it. But just in case it help.

Protractor- Generic wait for URL to change

Phox answered 7/8, 2017 at 19:11 Comment(1)
This is the correct answer and a much more reliable way to check the URL.Wringer

© 2022 - 2024 — McMap. All rights reserved.