简体   繁体   中英

Get WebElement text content with Selenium Driver in javascript

I would like to check if the element I retrieved using its id contains the expected text value.

var driver = require('selenium-webdriver');
var By = driver.By;

var elem = this.driver.findElement(By.id('my_id'));
assert.equal(elem.getText(), 'blablabla');

Unfortunately this isn't the way to go:

 AssertionError: ManagedPromise {
   flow_:
    ControlFlow {
      propagateUnhandledRejections_: true,
      activeQueue_:
       TaskQueue {
      == 'blablabla'

I can't manage to find an example how to do this simple check.

The reason for that is that elem.getText() is actually a Promise . That means, that it will be executed asynchronously, and it's result will be available at a later point in time. The return value of getText() is not the actual text, but a pointer to that asynchronous execution.

To actually use the return value of getText() (once it has been computed), use the then method and pass it a function. This anonymous function will then get called once the text has been computed, and you can work with it (for instance, assert that it is equal to an expected value):

var elem = driver.findElement(By.id('mydiv'));
elem.getText().then(function(s) {
  assert.equal(s, "content");
});

Or, if you prefer the use of lambda expressions :

elem.getText().then(s => assert.equal(s, "content"));

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