简体   繁体   中英

How do you store the result of getText in a variable to use later on in Nightwatch?

I'm new to Nightwatch.js.

I was wondering how I can store the result of the getText command into a variable to be used outside of the command.

This is my code now:

var endDate;

client.getText("span.date", function(result){
   LOGGER(`INSIDE FXN ${result.value}`);
   endDate = result.value;
});

LOGGER(`OUTSIDE FXN ${endDate}`);

Results:

*******INSIDE FXN 3/30/2018*******
*******OUTSIDE FXN UNDEFINED*******

As you can see, I'm trying to get the text in span.date and displaying it with LOGGER (which works successfully inside the function). Once we move outside of the callback function of getText, when I display it with LOGGER, it outputs undefined.

It's really important that the date is store in a variable because I intend to use it in a test element (for a UI Smoke test).

Thank you in advance!

Hmm without out being able to test it myself, I'd just have to guess.

If i had to take a guess, I'd speculate that getText is running after the second LOGGER

let result;

function changeResult(){
  result = 5;
}

// This is probably when your code is getting logged
console.log(result);

changeResult();
// here is when you would get result 
console.log(result);

https://nightwatchjs.org/api/getText.html#apimethod-page

My guess was correct.

per the documentation

module.exports = {
  demoTest(browser) {
    browser.getText('#main ul li a.first', function(result) {
      this.assert.equal(typeof result, 'object);
      this.assert.strictEqual(result.status, 0); // only when using Selenium / JSONWire
      this.assert.equal(result.value, 'nightwatchjs.org');
    });

    // with explicit locate strategy
    browser.getText('css selector', '#main ul li a.first', function(result) {
      console.log('getText result', result.value);
    });

    // with selector object - see https://nightwatchjs.org/guide#element-properties
    browser.getText({
      selector: '#main ul li a',
      index: 1
    }, function(result) {
      console.log('getText result', result.value);
    });

    browser.getText({
      selector: '#main ul li a.first',
      timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present
    }, function(result) {
      console.log('getText result', result.value);
    });
  },

  demoTestAsync: async function(browser) {
    const result = await browser.getText('#main ul li a.first');
    console.log('getText result', result);
  }
}

which means you can.then() to get your result

My way is storing result in browser.globals.variableName,

browser.globals.variableName = 'some_value'

Then you can use browser.globals.variableName anywhere in nightwatch.

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