WitVault
WitVault

Reputation: 24130

Perform click operation in succession on dynamic list of selected elements in nightmare js

I just started using nightmare. I was using it on my web page for testing purpose.

I have following user interface.

menu

tab1 | tab2 | tab3 ......(dynamically generated tabs)

container div for selected tab

       selected tab data

I got the dom element which contains the menu.

I don't know to how to perform click on each tab and get the selected tab data.

After reading the docs I couldn't figure out this, neither there are any example for this.

I was able to do only this -

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare
  .goto('http://www.example.com')
  .wait('#menu')
  .evaluate(function () {
      var menuDiv = document.querySelector('div#menu.content-disp');
      var menuAnchors = menuDiv.querySelectorAll('a[href]');

      var res = "";
      for(var i =0;i<menuAnchors.length;i++){
          res+=menuAnchors[i].innerText;
      }

      return res;
  })
  .end()
  .then(function (result) {
      console.log(result)
  })
  .catch(function (error) {
    console.error('Search failed:', error);
  });

I am using nightmare version

"dependencies": {
    "nightmare": "^2.8.1"
  }

Upvotes: 0

Views: 445

Answers (1)

Ross
Ross

Reputation: 2468

After you've built the list of anchors, you'll need to iterate over them, which with Promises is a non-trivial task. Consider the following, which iterates over your results and gets the title for each page:

nightmare.then((result) => 
  result.reduce(function(accumulator, url) {
    return accumulator.then(function(results) {
      return nightmare.goto(url)
        .wait('body')
        .title()
        .then(function(result){
          results.push(result);
          return results;
        });
    });
  }, Promise.resolve([])).then(function(results){
    console.dir(results);
});

You may want to give "Asynchronous Operations and Loops" at nightmare-examples a read. That should help you get started.

Upvotes: 1

Related Questions