From 611290deb53d88e310e0232e984c7ab7d0bb4971 Mon Sep 17 00:00:00 2001 From: David Baker Date: Wed, 27 Jul 2022 18:46:19 +0100 Subject: [PATCH 1/2] Add a flushSync() method Hopefully all explained in the comments / doc strings --- src/index.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/index.ts b/src/index.ts index 5cfb0dd..4143b03 100644 --- a/src/index.ts +++ b/src/index.ts @@ -96,6 +96,37 @@ class HttpBackend { }); }; + /** + * Flush any requests that have been made and are in the queue, waiting for + * responses. Other flush methods set timers to wait for requests to arrive, + * so if your test uses fake timers, you probably want to use this method, + * however it is up to you to make sure the request has been made and is in + * the queue at the point of calling this method. + * + * @param path The path to flush (optional) default: all. + * @param numToFlush numToFlush The maximum number of things to flush (optional), default: all. + * + * @return The number of requests flushed + */ + public flushSync (path: string | undefined, numToFlush?: number): number { + // Note that an alternative to this method could be to let the app pass + // in a setTimeout function so it could give us the real setTimeout function + // rather than the faked one. However, if you're running with fake timers + // the only thing setting a real timer would do is allow pending promises + // to resolve/reject. The app would have no way to know when the correct, + // non-racy point to tick the timers is. + console.log(`${Date.now()} HTTP backend flushing (sync)... (path=${path}` + + ` numToFlush=${numToFlush}` + + ")" + ); + + let numFlushed = 0; + while ((!numToFlush || numFlushed < numToFlush) && this._takeFromQueue(path)) { + ++numFlushed; + } + return numFlushed; + } + /** * Respond to all of the requests (flush the queue). * @param {string} path The path to flush (optional) default: all. From fae8b12f2c85cfe11691037b12cd0e51188197ae Mon Sep 17 00:00:00 2001 From: David Baker Date: Thu, 28 Jul 2022 09:40:57 +0100 Subject: [PATCH 2/2] Formatting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Šimon Brandner --- src/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index 4143b03..4e2d186 100644 --- a/src/index.ts +++ b/src/index.ts @@ -115,9 +115,9 @@ class HttpBackend { // the only thing setting a real timer would do is allow pending promises // to resolve/reject. The app would have no way to know when the correct, // non-racy point to tick the timers is. - console.log(`${Date.now()} HTTP backend flushing (sync)... (path=${path}` - + ` numToFlush=${numToFlush}` - + ")" + console.log( + `${Date.now()} HTTP backend flushing (sync)... (path=${path} ` + + `numToFlush=${numToFlush})` ); let numFlushed = 0;