简体   繁体   中英

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);

How to print the Value outside the promise loop which needs to compare with another variable? I need this 'value' to compare not in except statement. Please guide me.

This is a typical example of asynchronous programming in JavaScript. You can refer Protractor: what's the difference between ignoreSynchronization and async/await in Protractor this answer to understand how execution happens

Now to answer your question, you can use async/ await instead of.then and store the value.

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);
});

Hope this will solve your answer

Edit:

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);
  });

It would be better to use async/await in this scenario. However, if you have to use the approach you posted in your snippet you would do it like this.

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);
  }
});

Try this out!

use async/await instead of promise chaining. Writing code with promise chaining is a bit complex and not gives a flexible approach to write code. 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();

now you can print the Value outside and compare with another variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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