Javascript 如何在量角器测试中使用 browser.getCurrentUrl()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29129186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use browser.getCurrentUrl() in a protractor test?
提问by Blaise
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 getCurrentUrlalways fails when placed after a waitForAngular()statement.
getCurrentUrl当放在waitForAngular()语句之后时,似乎总是失败。
The error output is too vague:
错误输出太模糊:
UnknownError: javascript error: document unloaded while waiting for result
UnknownError:javascript 错误:文档在等待结果时已卸载
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,
如果我getCurrentUrl()在点击链接之前,
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,
如果我getCurrentUrl()在点击链接后,
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 UnknownErroroutput above. What went wrong?
UnknownError上面的输出在量角器中抛出一个错误。什么地方出了错?
回答by alecxe
Instead of waitForAngular()call, wait for the URL to change:
等待 URL 更改而不是waitForAngular()调用:
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.
最初由 @juliemr 在UnknownError: javascript error: document unloaded while waiting for result 建议。
回答by Anju Thomas
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);
});
})
});

