1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 * Provide polling-based "wait for" functionality, and defines some useful
13 /** @suppress {duplicate} */
14 var browserTest = browserTest || {};
17 browserTest.Timeout = {
23 browserTest.Predicate = function() {};
25 /** @return {boolean} */
26 browserTest.Predicate.prototype.evaluate = function() {};
28 /** @return {string} */
29 browserTest.Predicate.prototype.description = function() {};
32 * @param {browserTest.Predicate} predicate
33 * @param {number=} opt_timeout Timeout in ms.
36 browserTest.waitFor = function(predicate, opt_timeout) {
39 * @param {function(boolean):void} fulfill
40 * @param {function(Error):void} reject
42 function (fulfill, reject) {
43 if (opt_timeout === undefined) {
44 opt_timeout = browserTest.Timeout.DEFAULT;
47 var timeout = /** @type {number} */ (opt_timeout);
48 var end = Number(Date.now()) + timeout;
49 var testPredicate = function() {
50 if (predicate.evaluate()) {
51 console.log(predicate.description() + ' satisfied.');
53 } else if (Date.now() >= end) {
54 reject(new Error('Timed out (' + opt_timeout + 'ms) waiting for ' +
55 predicate.description()));
57 console.log(predicate.description() + ' not yet satisfied.');
58 window.setTimeout(testPredicate, 500);
67 * @return {browserTest.Predicate}
69 browserTest.isVisible = function(id) {
70 var pred = new browserTest.Predicate();
71 pred.evaluate = function() {
72 /** @type {HTMLElement} */
73 var element = document.getElementById(id);
74 browserTest.expect(Boolean(element), 'No such element: ' + id);
75 return element.getBoundingClientRect().width !== 0;
77 pred.description = function() {
78 return 'isVisible(' + id + ')';
85 * @return {browserTest.Predicate}
87 browserTest.isEnabled = function(id) {
88 var pred = new browserTest.Predicate();
89 pred.evaluate = function() {
90 /** @type {Element} */
91 var element = document.getElementById(id);
92 browserTest.expect(Boolean(element), 'No such element: ' + id);
93 return !element.disabled;
95 pred.description = function() {
96 return 'isEnabled(' + id + ')';