Await asynchronous assertions and failures
Quick answer
Asynchronous tests must wait for the work being tested. A test that finishes before its promise or callback completes can falsely appear to pass.
How it works
In node:test, use an async test callback and await the operation and its assertions, or return the relevant promise. assert.rejects waits for a promise to reject and can check the error type. Use assert.throws for synchronous throwing functions, not promise rejection. Control deferred outcomes instead of relying on arbitrary sleeps. If the test uses callback completion, use the runner’s documented callback contract rather than mixing it with a returned promise.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const assert=require("node:assert/strict");await assert.rejects(async()=>{throw new RangeError("limit");},RangeError);console.log("rejection checked");})()Expected console output:
rejection checkedThe assertion completes after observing the expected rejection.
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const assert=require("node:assert/strict");let release;const p=new Promise(r=>{release=r;});const work=p.then(x=>x*2);release(4);assert.strictEqual(await work,8);console.log("fulfilled",await work);})()Expected console output:
fulfilled 8Explicit completion drives the asynchronous transformation.
Common mistakes
Do not forget to await assert.rejects. A timeout is a guard against a hung test, not evidence that a desired operation completed.
Practice
Write a test that checks fulfillment and rejection of an injected asynchronous loader without using real network or sleep.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Await asynchronous assertions and failures — Knowledge Check
Apply the concept and reason about local example output.
What must an async test do with its final relevant promise?
Which assertion checks rejection of a promise?
Why prefer a controlled pending promise over a fixed sleep?
What is the exact console output in Await asynchronous assertions and failures example 1?
(async () => {const assert=require("node:assert/strict");await assert.rejects(async()=>{throw new RangeError("limit");},RangeError);console.log("rejection checked");})()What is the exact console output in Await asynchronous assertions and failures example 2?
(async () => {const assert=require("node:assert/strict");let release;const p=new Promise(r=>{release=r;});const work=p.then(x=>x*2);release(4);assert.strictEqual(await work,8);console.log("fulfilled",await work);})()