1

Related questions:

Whenever I load my web-page, I need to wait for ajax calls to complete. I currently do this with:

browser.waitForElementNotPresent(
  "cssSelector_For_HTML_afterAJAXComplete",
  10000 //timeout
);

This adds an extra assertion to my test though, and makes the test-count for the report artificially larger than necessary.

Any ideas?

Community
  • 1
  • 1
Rafael Emshoff
  • 2,541
  • 1
  • 35
  • 47
  • It turned out that using [nightwatch-cucumber](https://github.com/mucsi96/nightwatch-cucumber) gives me the necessary wrappers to make nightwatch test reports more fitting. I recommend using this library for your tests. – Rafael Emshoff Sep 28 '16 at 15:47

1 Answers1

1

Ok, I hacked something together. I'm basically sending javascript to the console in selenium using browser.execute(function, params, callback)

  function waitForElement_NoPassFail(selector, timeout){
    browser.execute(function(selector, timeout, done){
      let intervalId;
      var p1 = new Promise(function(resolve, reject){
        intervalId = setInterval(function(){
          let itemArray = document.querySelectorAll(selector);
          if(itemArray.length == 1){
            clearInterval(intervalId);
            resolve(true); //element found
          } else if(itemArray.length>1){
            reject(false); //too many elements found, because of ambiguous selector
          }
        }, 100);
      });
      var p2 = new Promise(function(resolve, reject){
        setTimeout(reject,timeout, false); //timeout reached
      });
      return Promise.race([p1, p2]).then(function(result){
        done(result);
      });
    },
    [selector, timeout],
    function(result){
      if(!result){
        throw "Element: " + selector + " wasn't found after " + timout + " ms.";
      } else {
        console.log("Element found within timeout limits.") //doesn't trigger assert=ok
      }
    });
  };

  waitForElement_NoPassFail(
    "cssSelector_that_Is_Valid_after_AjaxIsComplete",
    10000 //timeout
  );

This can be extended in various ways, for example to support xPath. You could use the nightwatch global variable for element checking frequency when waiting. Write a comment if you need the help.

Rafael Emshoff
  • 2,541
  • 1
  • 35
  • 47