Returning Promises from Tests
You'll learn how to write async tests by simply returning a Promise, letting the test runner wait automatically for resolution or rejection.
The Core Idea
Instead of using the done callback, you can return a Promise directly from your test function. The test runner will automatically wait for that Promise to resolve (test passes) or reject (test fails). This approach is cleaner and more intuitive than manually calling done().
When you return a Promise:
- If it resolves, the test passes
- If it rejects, the test fails with the rejection reason
- The test runner won't complete the test until the Promise settles
How It Works
it('should fetch user data', () => {
return fetchUser(1).then(user => {
assert.strictEqual(user.name, 'Alice');
});
});
The test runner sees the returned Promise and waits. If fetchUser resolves and the assertion passes, the test succeeds. If the Promise rejects or the assertion fails, the test fails.
Think of it like this: You're handing the test runner a "ticket" (the Promise) and saying, "Don't mark this test complete until you can redeem this ticket." The runner patiently waits for redemption (resolution) or learns the ticket is invalid (rejection).
Common Pattern
it('should reject on invalid input', () => {
return validateInput('').catch(error => {
assert.strictEqual(error.message, 'Input required');
});
});
Notice there's no done callback — just return the Promise chain.
Key Takeaway: Return a Promise from your test function to handle async operations cleanly; the test runner automatically waits for resolution (pass) or rejection (fail), eliminating the need for manual done() callbacks.