транспортир, как получить HREF, несколько значений - PullRequest
0 голосов
/ 29 июня 2018

Как я могу получить значение 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 различных ссылок, чтобы получить

Я использую:

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.

Ответы [ 2 ]

0 голосов
/ 21 мая 2019

Я пошел по этому пути немного по-другому. Мне нравится, что я могу легко добавить больше проверки и ожиданий для каждого элемента в цикле; надеюсь, кто-то еще найдет это полезным. Любые отзывы приветствуются!

// 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);
0 голосов
/ 29 июня 2018

Только для получения всех 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

Дайте мне знать, если у вас есть какие-либо вопросы или предоставленный код не сработает. (не тестировал)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...