Alister Scott Alister Scott - 3 months ago 8
Javascript Question

Capture WebdriverJs value for use outside of block

I am trying to work out how to return a value from a block that uses a promise to retrieve the value when using WebDriverJs + Mocha.

I have this example code to try to show where I face the problem, the mocha test 1) fails as it doesn't use the value in a nested

test.it
block, whereas test 2) passes.

import assert from 'assert';
import test from 'selenium-webdriver/testing';
import webdriver from 'selenium-webdriver';

test.describe( 'Capture value from promise', function() {
this.timeout( 20000 );

let title, driver;

test.before( 'Start Browser', function() {
driver = new webdriver.Builder().forBrowser( 'chrome' ).build();
} );

test.describe( '1) Capture page title without block', function() {
test.it( 'Get and use page title', function() {
driver.get( 'https://WordPress.com' );
title = driver.getTitle().then( ( innerTitle ) => {
return innerTitle;
} );
console.log( title ); //promise
return assert.equal( title, 'WordPress.com: Create a free website or blog' );
} );
} );

test.describe( '2) Capture page title with block', function() {
test.it( 'Get page title', function() {
driver.get( 'https://WordPress.com' );
return driver.getTitle().then( ( innerTitle ) => {
title = innerTitle;
} );
} );

test.it( 'Use page title', function() {
console.log( title ); // actual title
return assert.equal( title, 'WordPress.com: Create a free website or blog' );
} );
} );
} );


If I want to use the returned value without nesting another
test.it
block is there a way to wait for the promise to be resolved?

Answer

To take Louis's answer a step further, you can use the Control Flow mechanism directly to guarantee that steps will be executed in the given order:

test.it( '3) Capture page title with controlFLow', function() {
  let flow = driver.controlFlow();
  driver.get( 'https://WordPress.com' );
  let title = "";
  flow.execute( function() {
    return driver.getTitle().then( ( innerTitle ) => {
      title = innerTitle;
      } );
  } );

  flow.execute( function() {
    console.log( title ); // actual title
    assert.equal( title, 'WordPress.com: Create a free website or blog' );
  } );
} );
Comments