OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 /** |
| 6 * @fileoverview |
| 7 * Provide polling-based "wait for" functionality, and defines some useful |
| 8 * predicates. |
| 9 */ |
| 10 |
| 11 'use strict'; |
| 12 |
| 13 /** @suppress {duplicate} */ |
| 14 var browserTest = browserTest || {}; |
| 15 |
| 16 /** @enum {number} */ |
| 17 browserTest.Timeout = { |
| 18 NONE: -1, |
| 19 DEFAULT: 5000 |
| 20 }; |
| 21 |
| 22 /** @interface */ |
| 23 browserTest.Predicate = function() {}; |
| 24 |
| 25 /** @return {boolean} */ |
| 26 browserTest.Predicate.prototype.evaluate = function() {}; |
| 27 |
| 28 /** @return {string} */ |
| 29 browserTest.Predicate.prototype.description = function() {}; |
| 30 |
| 31 /** |
| 32 * @param {browserTest.Predicate} predicate |
| 33 * @param {number=} opt_timeout Timeout in ms. |
| 34 * @return {Promise} |
| 35 */ |
| 36 browserTest.waitFor = function(predicate, opt_timeout) { |
| 37 return new Promise(function(fulfill, reject) { |
| 38 if (opt_timeout === undefined) { |
| 39 opt_timeout = browserTest.Timeout.DEFAULT; |
| 40 } |
| 41 var end = Number(new Date()) + opt_timeout; |
| 42 var testPredicate = function() { |
| 43 if (predicate.evaluate()) { |
| 44 console.log(predicate.description() + ' satisfied.'); |
| 45 fulfill(); |
| 46 } else if (Number(new Date()) >= end) { |
| 47 reject(new Error('Timed out (' + opt_timeout + 'ms) waiting for ' + |
| 48 predicate.description())); |
| 49 } else { |
| 50 console.log(predicate.description() + ' not yet satisfied.'); |
| 51 window.setTimeout(testPredicate, 500); |
| 52 } |
| 53 }; |
| 54 testPredicate(); |
| 55 }); |
| 56 }; |
| 57 |
| 58 /** |
| 59 * @param {string} id |
| 60 * @return {browserTest.Predicate} |
| 61 */ |
| 62 browserTest.isVisible = function(id) { |
| 63 var element = document.getElementById(id); |
| 64 browserTest.expect(element, 'No such element: ' + id); |
| 65 return { |
| 66 evaluate: function() { |
| 67 return element.getBoundingClientRect().width != 0; |
| 68 }, |
| 69 description: function() { |
| 70 return 'isVisible(' + id + ')'; |
| 71 } |
| 72 }; |
| 73 }; |
| 74 |
| 75 /** |
| 76 * @param {string} id |
| 77 * @return {browserTest.Predicate} |
| 78 */ |
| 79 browserTest.isEnabled = function(id) { |
| 80 var element = document.getElementById(id); |
| 81 browserTest.expect(element, 'No such element: ' + id); |
| 82 return { |
| 83 evaluate: function() { |
| 84 return !element.disabled; |
| 85 }, |
| 86 description: function() { |
| 87 return 'isEnabled(' + id + ')'; |
| 88 } |
| 89 }; |
| 90 }; |
OLD | NEW |