How to use browser.getCurrentUrl() in a protractor test?
Solution 1
Instead of waitForAngular()
call, wait for the URL to change:
browser.wait(function() {
return browser.getCurrentUrl().then(function(url) {
return /index/.test(url);
});
}, 10000, "URL hasn't changed");
Originally suggested by @juliemr at UnknownError: javascript error: document unloaded while waiting for result.
Solution 2
This piece of code works correctly
var handlePromise = browser.driver.getAllWindowHandles();
handlePromise.then(function (handles) {
// parentHandle = handles[0];
var popUpHandle = handles[1];
// Change to new handle
browser.driver.switchTo().window(popUpHandle).then(function() {
return browser.getCurrentUrl().then(function(url) {
console.log("URL= "+ url);
});
})
});
Comments
-
Blaise over 3 years
I have been struggling with these lines of Protractor code today:
element(by.linkText("People")).click(); browser.waitForAngular(); var url = browser.getCurrentUrl(); ...
It appears that
getCurrentUrl
always fails when placed after awaitForAngular()
statement.The error output is too vague:
UnknownError: javascript error: document unloaded while waiting for result
So, what is the correct way to click on a hyperlink and check the new url?
Here are my tests:
If I
getCurrentUrl()
before the link is clicked,it('can visit people page', function () { var url = browser.getCurrentUrl(); element(by.linkText("People")).click(); expect(true).toBe(true); });
The test will pass.
If I
getCurrentUrl()
after the link is clicked,it('can visit people page', function () { var url = browser.getCurrentUrl(); element(by.linkText("People")).click(); expect(true).toBe(true); url = browser.getCurrentUrl(); });
An error is thrown in Protractor with the
UnknownError
output above. What went wrong? -
Jeremy Kahan almost 7 yearsJim Evans on several Selenium-related posts (such as groups.google.com/forum/#!topic/selenium-users/TgLNU631vmk) points out that "you may not assume there's an order to the handles returned by getWindowHandles(). It's a common mistake, but the handles are explicitly not in any order." I actually used code that SO posted that did so, and lost lots of time figuring out you cannot count on that.