From f5e706b846779783dc2e3b709ada98ea99a66140 Mon Sep 17 00:00:00 2001 From: Lucas Werkmeister Date: Wed, 24 Sep 2025 20:57:00 +0200 Subject: [PATCH] Docs: Recommend async functions over assert.async() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the simple example from the documentation, the timeout problem doesn’t actually occur (if fetchDouble() synchronously throws an Error, QUnit reports a test failure despite the assert.async() still being outstanding), but in more complicated tests it can still happen. We’ve recently migrated some tests in MediaWiki core and extensions to async+await syntax – see [1], [2], [3]. [1]: https://gerrit.wikimedia.org/r/c/mediawiki/extensions/VisualEditor/+/1026171 [2]: https://gerrit.wikimedia.org/r/c/mediawiki/core/+/1106934 [3]: https://gerrit.wikimedia.org/r/c/mediawiki/extensions/Wikibase/+/1188501 --- docs/api/assert/async.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/api/assert/async.md b/docs/api/assert/async.md index 348cd6a74..5314d808a 100644 --- a/docs/api/assert/async.md +++ b/docs/api/assert/async.md @@ -24,6 +24,11 @@ Instruct QUnit to wait for an asynchronous operation. `assert.async()` returns a callback function and pauses test processing until the callback function is called. The callback will throw an `Error` if it is invoked more often than the required call count. +Since [QUnit 1.16][], it is usually better to write asynchronous tests as [async functions][]. This ensures that tests fail early, rather than timing out, if an exception causes the `done` callback to not be called. + +[QUnit 1.16]: https://github.com/qunitjs/qunit/releases/tag/1.16.0 +[async functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function + ## See also * [Migration guide](../../upgrade-guide-2.x.md#introducing-assertasync) from QUnit 1.x `stop()` and `start()`. @@ -49,6 +54,16 @@ QUnit.test('async example', function (assert) { }); }); ``` + +Alternatively, this test can be written like this: + +```js +QUnit.test('async function example', async function (assert) { + const res = await new Promise((resolve) => fetchDouble(21, resolve)); + assert.strictEqual(res, 42, 'Result'); +}); +``` + ### Wait for multiple callbacks Call `assert.async()` multiple times to wait for multiple async operations. Each `done` callback must be called exactly once for the test to pass.