diff --git a/src/helper.ts b/src/helper.ts index 60cecab91e..6c82e6cd01 100644 --- a/src/helper.ts +++ b/src/helper.ts @@ -133,6 +133,8 @@ class Helper { resolveCallback = resolve; rejectCallback = reject; }); + + // Add listener. const listener = Helper.addEventListener(emitter, eventName, event => { try { if (!predicate(event)) @@ -142,20 +144,21 @@ class Helper { rejectCallback(e); } }); + + // Reject upon timeout. const eventTimeout = setTimeout(() => { rejectCallback(new TimeoutError(`Timeout exceeded while waiting for ${String(eventName)}`)); }, helper.timeUntilDeadline(deadline)); - function cleanup() { + + // Reject upon abort. + abortPromise.then(rejectCallback); + + try { + return await promise; + } finally { Helper.removeEventListeners([listener]); clearTimeout(eventTimeout); } - return await Promise.race([promise, abortPromise]).then(r => { - cleanup(); - return r; - }, e => { - cleanup(); - throw e; - }); } static async waitWithDeadline(promise: Promise, taskName: string, deadline: number, debugName: string): Promise { diff --git a/test/page.spec.js b/test/page.spec.js index e09259b1f4..ee2fcefd64 100644 --- a/test/page.spec.js +++ b/test/page.spec.js @@ -345,6 +345,16 @@ describe('Page.waitForRequest', function() { }); }); +describe('Page.waitForEvent', function() { + it('should fail with error upon disconnect', async({page, server}) => { + let error; + const waitForPromise = page.waitForEvent('download').catch(e => error = e); + await page.close(); + await waitForPromise; + expect(error.message).toContain('Target closed'); + }); +}); + describe('Page.waitForResponse', function() { it('should work', async({page, server}) => { await page.goto(server.EMPTY_PAGE);