我正在尝试在cypress的每个循环中设置一个变量,以后再使用该变量。变量在循环中递增,但是当我使用它时在其外部变为零。您能否向我解释原因,以及如何纠正此问题?谢谢
public getNoEntries(fullName: string) : number
{
let noEntries: number = 0;
cy.get(this.employeeList).find('li').each((x) =>
{
var entryName = x.text().trim();
if (entryName.localeCompare(fullName)==0)
{
++noEntries;
cy.log("in loop: "+noEntries.toString());
}
});
cy.log('out of loop:'+noEntries);
return noEntries;
}
输出为:
循环中:1循环中:2循环中:3循环外:0
我希望它返回3。我该怎么做?
非常感谢。
正如cypress documentation中很好的解释,
您不能分配或使用任何赛普拉斯命令的返回值。命令已排队并异步运行。
因此,您可以使用调用函数cypress命令本身将getNoEntries()函数代码链接起来,而不是使用函数的返回值。
也'outofloop'为0,因为变量new值的范围以cy.get()本身结尾。要获得变量的新值,可以在第一个命令的then()中链接第二个log(),如下所示。
let noEntries: number = 0;
cy.get(this.employeeList).find('li').each((x) =>
{
var entryName = x.text().trim();
if (entryName.localeCompare(fullName)==0)
{
++noEntries;
cy.log("in loop: "+noEntries.toString());
}
})
.then(()=>{
cy.log('out of loop:'+noEntries);
})