如何获取每个“ a”的href值?
<div class="nea-sidebar" _ngcontent-c2="">
<a class="sidebar-item active" href="#/test" _ngcontent-c2="" routerlinkactive="active" ng-reflect-router-link="test" ng-reflect-router-link-active="active">
<i class="sidebar-icon fas fa-play" _ngcontent-c2="" ng-reflect-klass="sidebar-icon fas" ng-reflect-ng-class="fa-play"></i>
<span class="sidebar-label" _ngcontent-c2="">Start Test</span></a>
<a class="sidebar-item" href="#/sequences" _ngcontent-c2="" routerlinkactive="active" ng-reflect-router-link="sequences" ng-reflect-router-link-active="active">
<i class="sidebar-icon fas fa-project-diagram" _ngcontent-c2="" ng-reflect-klass="sidebar-icon fas" ng-reflect-ng-class="fa-project-diagram"></i>
<span class="sidebar-label" _ngcontent-c2="">Sequences</span></a>
这只是代码的一部分,我有5种不同的href
我正在使用:
element.all(by.css('a')).count().then(function(numberOfTRs) {
for (let i = 1; i <= numberOfTRs; i ++) {
expect(element(by.css('a')).getAttribute('href')).toMatch('http://localhost:4200/#/sequence');
}
});
返回
returns:
- Expected 'http://localhost:4200/#' to match 'http://localhost:4200/#/sequence'.
- Expected 'http://localhost:4200/#' to match 'http://localhost:4200/#/sequence'.
- Expected 'http://localhost:4200/#' to match 'http://localhost:4200/#/sequence'.
- Expected 'http://localhost:4200/#' to match 'http://localhost:4200/#/sequence'.
- Expected 'http://localhost:4200/#' to match 'http://localhost:4200/#/sequence'.
- Expected 'http://localhost:4200/#' to match 'http://localhost:4200/#/sequence'.
Executed 1 of 1 spec (1 FAILED) in 22 secs.
答案 0 :(得分:0)
仅获取所有href
元素的所有a
值,您可以执行以下操作:
element.all(by.tagName('a')).map((function (el) {
return el.getAtrribute('href');
});
可能您要检查页面上是否存在一组链接。您可以实现以下目标:
// the urls you are expecting to be on the page
var expectedUrls = ['/home', '/sequence', '/other'];
element.all(by.tagName('a')).map((function (el) {
return el.getAttribute('href');
})).then(function (urls) {
urls.forEach(function (url) {
expect(expectedUrls.some(function (expUrl) {
return expUrl === url;
})).toBeTruthy();
});
});
element.all(by.tagName('a'))
收集所有元素
.map()
将所有元素转换为其href
值。
array.some()
检查至少一个元素的填充条件
=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
让我知道您是否有任何疑问或提供的代码无法解决。 (未测试)
答案 1 :(得分:0)
我采用了一种稍微不同的方式。我喜欢这样,我可以轻松地添加更多验证,并期望对循环中的每个元素进行验证。希望其他人对此有所帮助。任何反馈表示赞赏!
// Ideally you'd be using POM
const tempElements = element.all(by.css('a'));
// Check for '/' in url and print list of hrefs to console.
async function getElementsLinks(elements: ElementArrayFinder){
const tempList = [];
for (let i = 0; i < await elements.count(); i++) {
const temp = await elements.get(i).getAttribute('href');
expect(temp).toContain('/');
tempList.push(temp);
}
console.log(tempList);
}
// Call the function on an ElementArrayFinder object
await getElementsLinks(tempElements);