Testing Callback-Based APIs
What you'll learn: How to test older callback-based code by either wrapping it in promises or using the done() callback pattern.
The Challenge
Many legacy JavaScript APIs use callbacks instead of promises. When testing these, you can't just return a promise or await a result—the test runner doesn't know when your asynchronous operation completes. You need explicit strategies to signal test completion.
Strategy 1: The Done Callback
Test runners like Jest, Mocha, and Node's test runner provide a done() callback parameter. Call it when your async operation finishes:
it('should handle callback-based function', (done) => {
fetchDataWithCallback((error, data) => {
if (error) {
done(error); // Fail the test
return;
}
assert.strictEqual(data.status, 'success');
done(); // Signal completion
});
});
Remember: If you forget to call done(), the test will timeout. If the callback never fires, that's actually good—the timeout reveals the bug.
Strategy 2: Promisification
Wrap the callback-based API in a promise, then use async/await (which you already know):
function promisify(callbackFn) {
return new Promise((resolve, reject) => {
callbackFn((error, result) => {
if (error) reject(error);
else resolve(result);
});
});
}
it('should handle promisified callback', async () => {
const data = await promisify(fetchDataWithCallback);
assert.strictEqual(data.status, 'success');
});
This approach is cleaner for multiple async assertions and works better with modern test patterns.
Key Takeaway: Test callback-based APIs using either the done() callback to explicitly signal completion, or promisify them to leverage cleaner async/await syntax—choose based on whether you're modernizing or maintaining legacy test style.