繁体   English   中英

Protractor:count() 在 promise 循环之外不起作用

[英]Protractor:count() doesn't work outside promise loop

var notifications = element.all(by.xpath("//div[@class='notification-content']"));
notifications.count().then(function (value) {
    console.log(value);
});
 console.log(value);

如何在需要与另一个变量进行比较的 promise 循环外打印值? 我需要这个“值”来比较不在 except 语句中。 请指导我。

这是JavaScript中异步编程的一个典型例子,可以参考Protractor中:what's the difference between ignoreSynchronization and async/await这个答案了解执行是如何发生的

现在回答您的问题,您可以使用 async/await 而不是 .then 并存储值。

it('should get count', async () => {
  await browser.get("url of application");
  let count = await element.all(by.xpath("//div[@class='notification- content']")).count();
  console.log(count);
});

希望这能解决您的问题

编辑:

it("test", () => {
    let count1, count2;
    browser.get("url of application");
    var notifications = element.all(by.xpath("//div[@class='notification-content']"));
    count1 = notifications.count();
    var notifications = element.all(by.xpath("//div[@class='notification-content']"));
    count2 = notifications.count();
    expect(count1).toBe(count2);
  });

在这种情况下使用 async/await 会更好。 但是,如果您必须使用您在代码段中发布的方法,您会这样做。

var notifications1 = element.all(by.xpath("//div[@class='notification-content1']"));
var notifications2 = element.all(by.xpath("//div[@class='notification-content2']"));

notifications1.count().then(function (count1) {
  notifications2.count().then(function (count2) {
    expect(count1).toEqual(count2);
  }
});

试试这个!

使用async/await而不是 promise 链接。 使用 promise 链接编写代码有点复杂,并且没有提供灵活的代码编写方法。 https://www.protractortest.org/#/async-await

let notifications;
let value;

async GetElementCount() {
   notifications = await element.all(by.xpath('//div[@class=\'notification-content\']'));
   return notifications.count();
}

value = await GetElementCount();

现在您可以在外部打印值并与另一个变量进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM