Equivalent behaviour of 'jQuery.active' in

2019-09-04 14:22发布

问题:

In my c# selenium webdriver tests I occasionally have to make use of:

public void WaitForJQuery(TimeSpan timeout)
{
    var wait = new WebDriverWait(driver, timeout);
    wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0"));
}

This waits up until the specified 'timeout' for jQuery calls to finish. I was wondering if there was an equivalent I could use for the q.js library?

I'm a tester not a webdesigner and have very little experience with the q library, browsing through the documentation for it I can't see any relevant static properties that might contain the information I desire.

回答1:

No, Q keeps track of each promise independantly so the only record it maintains is unhandled rejections (for error reporting purposes) It wouldn't be too hard to build something though:

var pending = 0;
function register(operation) {
  pending++
  return Q(operation)
    .finally(function() { pending--; });
}

If you call register(promise) every time you create a promise, you'll get the result you're after by just testing whether pending === 0

This register method can also be used to check for pending jQuery promises (or any other type of promise that has a working then method) since Q will assimilate them.