我正在测试一个输出一些数据的页面,我想将该数据捕获到一个 JSON 对象中。数据显示如下(html格式)
<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>
我希望生成的 JSON 对象是:
[ {
name: "Joe",
web: {
text: "joessite.com",
link: "http://joessite.com"
}
},
{
name: "Frank",
web: {
text: "frankssite.com",
link: "http://frankssite.com"
}
} ]
所以我写了下面的代码:
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;
};
不幸的是,我的实际结果是(注意第一个“web”是空白的)。
[ {
name: "Joe",
web: { }
},
{
name: "Frank",
web: {
text: "frankssite.com",
link: "http://frankssite.com"
}
} ]
我做错了什么或者我的代码需要改进什么?
(我使用的是 Protractor 版本 3.2.2)
最佳答案
我会使用 map()
使用 protractor.promise.all()
:
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]
}
}
});
});
};
关于javascript - 如何从 Protractor 中的 promise 中获取嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38272173/