[gold] test_util.js: Extract buildEventPromise() from eventPromise() in preparation for noEventPromise() in follow-up CL.
Function noEventPromise() is introduced in https://skia-review.googlesource.com/265077.
Bug: skia:9525
Change-Id: Ic40529c54cc0f8a2ad5b2be9e6b826e0f61e4646
Reviewed-on: https://skia-review.googlesource.com/c/buildbot/+/265149
Reviewed-by: Kevin Lubick <kjlubick@google.com>
Commit-Queue: Leandro Lovisolo <lovisolo@google.com>
diff --git a/golden/modules/test_util.js b/golden/modules/test_util.js
index e34c359..d7f433d 100644
--- a/golden/modules/test_util.js
+++ b/golden/modules/test_util.js
@@ -57,6 +57,31 @@
* @return {Promise} A promise that will resolve to the caught event.
*/
export function eventPromise(event, timeoutMillis = 5000) {
+ const eventCaughtCallback = (resolve, _, e) => resolve(e);
+ const timeoutCallback =
+ (_, reject) =>
+ reject(new Error(`timed out after ${timeoutMillis} ms ` +
+ `while waiting to catch event "${event}"`));
+ return buildEventPromise(
+ event, timeoutMillis, eventCaughtCallback, timeoutCallback);
+}
+
+/**
+ * Helper function to construct promises based on DOM events.
+ *
+ * @param event {string} Name of event to add a listener for at document.body.
+ * @param timeoutMillis {number} Milliseconds to wait before timing out.
+ * @param eventCaughtCallback {Function} Called when the event is caught with
+ * parameters (resolve, reject, event), where resolve and reject are the
+ * functions passed to the promise's executor function, and event is the
+ * Event object that was caught.
+ * @param timeoutCallback Called after timeoutMillis if no event is caught, with
+ * arguments (resolve, reject) as passed to eventCaughtCallback.
+ * @return {Promise} A promise that will resolve or reject based exclusively on
+ * what the callback functions do with the resolve and reject parameters.
+ */
+function buildEventPromise(
+ event, timeoutMillis, eventCaughtCallback, timeoutCallback) {
// The executor function passed as a constructor argument to the Promise
// object is executed immediately. This guarantees that the event handler
// is added to document.body before returning.
@@ -65,7 +90,7 @@
const handler = (e) => {
document.body.removeEventListener(event, handler);
clearTimeout(timeout);
- resolve(e);
+ eventCaughtCallback(resolve, reject, e);
};
// Skip setTimeout() call with timeoutMillis = 0. Useful when faking time in
// tests with sinon.useFakeTimers(). See
@@ -73,8 +98,7 @@
if (timeoutMillis !== 0) {
timeout = setTimeout(() => {
document.body.removeEventListener(event, handler);
- reject(new Error(`timed out after ${timeoutMillis} ms ` +
- `while waiting to catch event "${event}"`));
+ timeoutCallback(resolve, reject);
}, timeoutMillis);
}
document.body.addEventListener(event, handler);
@@ -87,4 +111,4 @@
*/
export function expectQueryStringToEqual(expected) {
expect(window.location.search).to.equal(expected);
-}
\ No newline at end of file
+}