量角器,承诺,参数和闭包 [英] Protractors, promises, parameters, and closures
问题描述
我现在要撕掉我的头发上剩下的东西. 而且我认为我的左膝盖失去了视力.
I'm now tearing out what little remains of my hair. And I think I've lost vision in my left knee.
我有两个有效的功能. 每个人都正确地接受一个参数. 我非常非常非常喜欢一个函数同时使用两个参数.
I have two functions that work. Each one takes a parameter correctly. I would dearly, so very dearly, love one function to take both parameters.
我有一个非常简单的数据结构:
I have a super simple data structure:
var stuff = [
{ name: "Stone", id: "cc45" },
{ name: "Hanley", id: "cc78" }
];
我希望遍历整个结构并对每个结构进行一个超级简单的测试.请注意:
I wish to loop through the structure and run a super simple test on each. Please observe:
for (var ii = 0; ii < stuff.length; ii++) {
var aTile = element(by.id(stuff[ii].id));
aTile.getText().then(
/* magical solution */
);
}
我所缺少的就是神奇的解决方案.在版本A(缺少魔术)中,我可以成功地看待量角器友善地抓取的文字:
All I'm missing the magical solution. In version A (which lacks magic) I can successfully regard the text that Protractor kindly grabbed:
aTile.getText().then((function (text) {
console.log(" --Protractor Grab--" + text);
}));
在版本B(也缺少魔术)中,我可以成功地看到我希望将量角器标记的文本与以下内容进行比较的数据:
In version B (which also lacks magic) I can successfully behold the data I wish to compare the Protractor-grabbed text to:
aTile.getText().then((function (test) {
console.log(" ==Stuff test==" + test);
})(stuff[ii].name));
无论我拉多少头发,我都无法做,就是让量角器将两者进行比较.实际上,我需要添加以下内容:
What I cannot do, no matter how much hair I pull, is to get Protractor to compare both. Effectively, I need to add this:
expect(protractorGrabbedText).toContain(expectedTextFromStuff);
请善待代码英雄,帮助我,我恳求你.
Please kind heroes of code, help me, I implore you.
推荐答案
这非常简单. expect()
方法能够做出隐式解析并使用结果与实际数据进行比较的能力.您可以使用如下所示的方法,
it's very simple. expect()
method have the capability to make a promise to resolve implicitly and use the result to compare with the actual data.You can use something like below,
for (var ii = 0; ii < stuff.length; ii++) {
var aTile = element(by.id(stuff[ii].id)).getText();
expect(aTile.getText()).toContain(stuff[ii].name) //This will take care of resolving the promises.
}
方法-2:
由于使用的是for循环,因此需要使用闭包来获取Promise中的ii
值.试试下面的代码.
Since you are using for loop, you need to use closures to get the value of ii
inside the promise. try the below code.
for (var ii = 0; ii < stuff.length; ii++) {
function closure(index){
element(by.id(stuff[index].id)).getText().then(function(text){
expect(text). toContain(stuff[index].name)
})
}
closure(ii)
}
这篇关于量角器,承诺,参数和闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!