Skip to content

Instantly share code, notes, and snippets.

@Ethan-Arrowood
Created March 25, 2025 20:30
Show Gist options
  • Select an option

  • Save Ethan-Arrowood/bc9d496ff80b2782fb9df29a0fa3895e to your computer and use it in GitHub Desktop.

Select an option

Save Ethan-Arrowood/bc9d496ff80b2782fb9df29a0fa3895e to your computer and use it in GitHub Desktop.
A polling function for use in Node.js unit tests.
import { setInterval } from 'node:timers/promises';
import assert from 'node:assert/strict';
/**
* A simple time-based polling function with a default timeout of 100ms.
*
* Some of the tests in this file require waiting for the file watcher to detect changes.
* Files systems are not precise, and this is the best way to test file watcher behavior.
*
* If a test is flaky because of this mechanism, first consider what might be causing the file system to be slow (i.e. blocking I/O).
* 100ms is quite short so for large operations (such as a large file write), it may be necessary to provide a longer timeout.
*
* @param {() => boolean | Promise<boolean>} condition
* @param {number} [timeout=100]
*/
async function poll(condition, timeout=100) {
for await (const startTime of setInterval(1, Date.now())) {
if ((Date.now() - startTime > timeout)) assert.fail('Timeout');
if (await condition()) break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment