Introduce polymorphic page.waitFor method

This patch:
- introduces page.waitForSelector to wait for the selector to appear
- introduces polymorphic page.waitFor method, which accepts
either string (and in this case is a shortcut for page.waitForSelector)
or number (and in this case it's a promisified timeout).

References #91.
This commit is contained in:
Andrey Lushnikov
2017-07-21 12:41:49 -07:00
parent 1891a49962
commit dc032b42b9
6 changed files with 108 additions and 39 deletions

View File

@@ -201,7 +201,7 @@ class FrameManager extends EventEmitter {
async function inPageWatchdog(selector, visible, timeout) {
const resultPromise = visible ? waitForVisible(selector) : waitInDOM(selector);
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(reject.bind(null, new Error(`waitFor failed: timeout ${timeout}ms exceeded.`)), timeout);
setTimeout(reject.bind(null, new Error(`waitForSelector failed: timeout ${timeout}ms exceeded.`)), timeout);
});
await Promise.race([resultPromise, timeoutPromise]);
@@ -342,17 +342,30 @@ class Frame {
return this._detached;
}
/**
* @param {(string|number)} target
* @param {!Object=} options
* @return {!Promise}
*/
waitFor(target, options = {}) {
if (typeof target === 'string' || target instanceof String)
return this.waitForSelector(target, options);
if (typeof target === 'number' || target instanceof Number)
return new Promise(fulfill => setTimeout(fulfill, target));
return Promise.reject(new Error('Unsupported target type: ' + (typeof target)));
}
/**
* @param {string} selector
* @param {!Object=} options
* @return {!Promise}
*/
async waitFor(selector, options = {}) {
waitForSelector(selector, options = {}) {
const timeout = options.timeout || 30000;
const awaitedElement = new AwaitedElement(() => this._frameManager._waitForSelector(this, selector, !!options.visible, timeout));
// Since navigation will re-install page watchdogs, we should timeout on our
// end as well.
setTimeout(() => awaitedElement.terminate(new Error(`waitFor failed: timeout ${timeout}ms exceeded`)), timeout);
setTimeout(() => awaitedElement.terminate(new Error(`waitForSelector failed: timeout ${timeout}ms exceeded`)), timeout);
this._awaitedElements.add(awaitedElement);
let cleanup = () => this._awaitedElements.delete(awaitedElement);