The Done Callback Pattern
What you'll learn: How to use the done() callback to tell test frameworks when an asynchronous test has finished executing.
Why Async Tests Need Special Handling
When you write tests for asynchronous code (like API calls, timers, or file operations), the test runner can't automatically know when your test is complete. Without proper signaling, the runner might finish the test before your async code runs, causing assertions to be skipped or false positives to occur.
How the Done Callback Works
Test frameworks like Mocha and Jest provide a done callback function as a parameter to your test. When you accept this parameter, the framework waits for you to call done() before considering the test complete.
Think of it like telling a friend "I'll text you when I'm ready to leave." Until they receive that text, they keep waiting. The done() callback is your test saying "Okay, I'm actually finished now."
it('should handle async operation', (done) => {
setTimeout(() => {
const result = 2 + 2;
expect(result).toBe(4);
done(); // Signal completion
}, 100);
});
Without calling done(), the test runner would exit immediately, never running your assertion inside the setTimeout.
Signaling Errors
If your async operation fails, pass an error to done():
it('should handle async errors', (done) => {
fetchData((err, data) => {
if (err) {
done(err); // Test fails with this error
} else {
expect(data).toBeDefined();
done();
}
});
});
Key Takeaway: The done callback pattern lets you explicitly control when an async test completes by calling done() after all asynchronous operations and assertions finish—if you forget to call it, your test will timeout.