首页 > 解决方案 > 有什么方法可以使用量角器测试加载的网页 url,尽管它会随机更改端口号并且 url 正在更改?

问题描述

我使用量角器测试网页,并使用预期条件类来验证登录页面,并且由于端口更改测试失败。有没有什么办法解决这一问题?

browser.wait(EC.urlContains('localhost:49153'), 10000);
browser.wait(EC.urlContains('http://localhost:49153/'), 10000).then(function() {
});

提前致谢!

标签: javascripttypescriptprotractore2e-testing

解决方案


如果您事先不知道端口号,您可以获取当前 url 并进行匹配或使用节点 URL API。

const currentUrl = await browser.getCurrentUrl();
// for example, the url we are trying to get is http://localhost:12345/login/some/foo

使用匹配

您可以使用正则表达式进行匹配。如果你喜欢正则表达式,这很有趣。

expect(currentUrl).toMatch(/localhost:\d+\/login\/some\/foo/);

使用节点 URL(WHATWG API):

你也可以使用 node url API 见https://nodejs.org/api/url.html 我喜欢这个版本只是因为它更容易阅读:

const currentHref = new URL(currentUrl);
expect(currentHref.protocol).toBe('http');
expect(currentHref.host).toBe('localhost');
// take a look at the chart, path includes path + search query
// but does not include hashes. If you have hashes, you'll need to change this.
expect(currentHref.path).toBe('/login/some/foo');

推荐阅读