2016-07-08 2 views
3

일부 데이터를 출력하는 페이지를 테스트 중이므로 해당 데이터를 JSON 객체로 캡처하고 싶습니다. 불행하게도,각도기에서 약속 한 중첩 JSON을 얻는 방법

var cardDataToJSON = function() { 
    var result = {}; 

    $$('cards card').each(function (card) { 
     card.$('#name').getText().then(function (text) { result["name"] = text; }); 

     var web = {}; 
     card.$('#web').getText().then(function (text) { 
      web["text"] = text; 
     }); 
     card.$('#web').getAttribute('href').then(function (href) { 
      web["href"] = href; 
     }); 

     result.web = web; 
    }); 

    return result; 
}; 

내 실제 :

[ { 
    name: "Joe", 
    web: { 
     text: "joessite.com", 
     link: "http://joessite.com" 
    } 
    }, 
    { 
    name: "Frank", 
    web: { 
     text: "frankssite.com", 
     link: "http://frankssite.com" 
    } 
    } ] 

그래서 나는 다음과 같은 코드를 작성 : 내 결과 JSON 객체가되고 싶어

<cards> 
    <card> 
    <div id="name">Joe</div> 
    <div id="web"> 
     <a target="_blank" href="http://joessite.com">joessite.com</a> 
    </div> 
    </card> 
    <card> 
    <div id="name">Frank</div> 
    <div id="web"> 
     <a target="_blank" href="http://frankssite.com">frankssite.com</a> 
    </div> 
    </card> 
</cards> 

(HTML에서) 다음과 같이 데이터가 나타납니다 결과는 첫 번째 "웹"이 비어 있음을 나타냅니다.

[ { 
    name: "Joe", 
    web: { } 
    }, 
    { 
    name: "Frank", 
    web: { 
     text: "frankssite.com", 
     link: "http://frankssite.com" 
    } 
    } ] 

내가 잘못했거나 개선해야 할 부분이 있습니까?

내가 protractor.promise.all()map()을 사용

답변

2

(내가 각도기 버전 3.2.2을 사용하고 있습니다) :

그것은 약속 간의 동기화 문제처럼 보인다
var cardDataToJSON = function() { 
    return $$('cards card').map(function (card) { 
     var name = card.$('#name').getText(), 
      web = card.$('#web a').getText(), 
      href = card.$('#web a').getAttribute('href'); 

     return protractor.promise.all([name, web, href]).then(function (values) { 
      return { 
       name: values[0], 
       web: { 
        text: values[1], 
        link: values[2] 
       } 
      } 
     }); 
    }); 
}; 
1

. 또 다른 방법은 JavaScript 호출을 만들어 실행 시간을 현저하게 줄일 수 있습니다.

browser.executeScript(function() { 
    return [].map.call(document.querySelectorAll('cards > card'), function(card) { 
    return { 
     name: card.querySelector('#name').textContent, 
     web: { 
     text: card.querySelector('#web a').textContent, 
     link: card.querySelector('#web a').getAttribute('href') 
     } 
    }; 
    }); 
}).then(function(result){ 
    console.log(result); 
});