我正在使用 Protractor 为 Angular 应用程序设置一套端到端测试。我正在遵循此 article 中详述的页面对象模型模式.我在涉及创建用户和验证数据是否已正确处理/保存的特定测试时遇到问题。本次测试的步骤如下:
1.) 通过让 protactor 将数据从用户对象发送到表单并提交来创建用户:
//models.js
TestUser = {
Title: 'Big Boss Man',
Email: 'theboss@gmail.com',
}
2.) 通过检查新创建用户的“帐户详细信息” View 中的数据,验证数据是否已正确处理/保存。此数据显示在如下表格中:
// accountdetails.html
<table class="account-details" summary="Account details">
<tbody>
<tr>
<th>Title:</th>
<td class="ng-binding">Big Boss Man</td>
</tr>
<tr>
<th>Email:</th>
<td class="ng-binding">theboss@gmail.com</td>
</tr>
</tbody>
</table>
3.) 使用一个简单的辅助方法,该方法使用 jasmine 的 toEqual() 方法比较两个传入对象的匹配键/值对:
compareTwoObjects: function(object1, object2) {
Object.keys(object1).forEach(function(key) {
expect(object2[key].getAttribute('value')).toEqual(object1[key]);
});
问题:我如何编写一个使用元素选择器查找表的方法,深入到 <th>
中和 <td>
元素,获取它们的文本值,并构建一个键/值对对象,我可以将其与原始 TestUser
进行比较目的?因为我显然不太了解 promise ,所以以下是我想出的:
getUserData: {
get: function() {
var userData = {};
$$('table[summary="Account details"] tbody tr')
.then(function(rowElements) {
rowElements.forEach(function(rowElement) {
rowElement.$('th').getText().then(function(label) {
rowElement.$('td').getText().then(function(text) {
userData[label.slice(0,-1)] = text;
// success! logs {Title: 'Big Boss Man', Email: 'theboss@gmail.com'}
// on completion of loop
console.log(userData);
});
});
});
});
// failure, logs an empty object
console.log(userData);
return userData;
}
}
我知道它不起作用,因为在上述 promise 得到解决之前返回了 userData。我该如何解决这个问题,或者我需要以不同的方式思考什么?
最佳答案
通过文本获取第th
元素,使用following-sibling
定位user字段值,构造user
对象:
var user = {
Title: row.element("//th[. = 'Title:']/following-sibling::td").getText(),
Email: row.element("//th[. = 'Email:']/following-sibling::td").getText()
};
示例用法:
expect(user).toEqual(TestUser);
请注意,user
是一个字段值是 promise 的对象,但是,自 expect()
is patched to resolve promises implicitly ,我们可以开始了——一旦所有的 promise 都得到解决,它应该做出断言。
如果您想抽象出字段名称并使其可重用,请使用 map()
:
var table = $("table.account-details");
var user = {};
table.all(".//th").map(function (elm) {
var key = elm.getText(),
value = elm.element(by.xpath("following-sibling::td")).getText();
user[key] = value;
});
expect(user).toEqual(TestUser);
关于javascript - 使用 Protractor 从 promise 中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29526030/